BinaryReader and BinaryWriter

Just like StreamReader and StreamWriter, BinaryReader and BinaryWriter are helper classes encapsulating a stream. Their goal is to ease the manipulation of binary files.

BinaryReader and BinaryWriter derive from Object.

In order to use those class, you must construct it, BinaryReader and BinaryWriter constructors always take a Stream object as parameters. This Stream object will be used as the underlying stream where the BinaryReader will read from or the BinaryWriter will write to.

The constructors you will use most often are:

Failed to execute the [code] macro

Using BinaryReader

Once you have created an instance of a BinaryReader, this instance is bound to the Stream you have passed to the constructor. If you want to work on another stream, you must create a new instance of BinaryReader

Using the BinaryReader is quite easy. This class offers a lot of method that allows you to read all primitive types. Those methods are ReadX where X represent the primitive type you want to read. X may have the following value: Boolean, Byte, Char, Double, Int16, Int32, Int64, SByte, Single, UInt16, UInt32, UInt64 or String.

Using BinaryWriter

Just like the BinaryReader, the BinaryWriter is bound to the stream you passed to it's constructor.

Writing to a stream using BinaryWriter is as simple as calling the Write method, passing it the primitive object that you wish to write.


Now that you now all the methods needed to use BinaryReader and BinaryWriter, I will show you how to use these class.

Failed to execute the [code] macro

At first, we create a FileStream object representing the file that we will output to.

Next, we create our BinaryWriter, passing it our FileStream object. So every call to Write will end up in our file.

Once we've perform all of our writings, we close our BinaryWriter. Closing the writer has the side-effect of closing the writer's underlying stream (in our case the FileStream object.

In order to read from the file we've just written, we need to reopen our FileStream before passing it to our BinaryReader constructor.

Once we have constructed our reader, we may call ReadX to retrieve what we've previously written. Notice that use must now the order of what you've written in order to read correctly.

Finally, we close our reader which also close our underlying stream.

Advantages and drawbacks


 Advantages  Drawbacks 
 Allow to read and write primitive types easily  Writing/Reading objects needs to implement specific code 

Related articles: