8 Binary File I/O

Binary file I/O is illustrated by the following program that dumps the contents of a file in hex.

8.1 BinaryReader

The following HexDump function uses a BinaryReader class to read a file in binary mode and dump its bytes:

8.2 Using Statement

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.