Binary file I/O is illustrated by the following program that dumps the contents of a file in hex.
The following HexDump function uses a BinaryReader class to read a file in binary mode and dump its bytes:
Opening and reading the file occurs in a using statement that takes care automatically closing the file at the end of the using block.
The using statement is lowered by the compiler roughly to the following code:
The finally statement gets executed regardless whether the try block is exited with normal control flow, due to return, break, continue or goto statement, or due to thrown exception.
A using statement can be used with all classes that implement the Closable interface such as StreamReader, StreamWriter, FileStream, MemoryStream, BinaryReader and BinaryWriter.