C# Programming > Data

Reading the Binary File

So now that we have written a binary file in C#, how do we read it?

BinaryWriter has a counterpart class called BinaryReader. BinaryReader can read the same data types that BinaryWriter can write. The fundamental difference between reading and writing is that when we read, we must know what type is being read. Unlike writing (which takes a single function with lots of overloads), BinaryReader has separate read methods for each type.

This is why it is important to write the file in a logical way from the beginning. It is also necessary to know the structure of the file (obvious but an important thing to remember).

Whenever BinaryReader calls a read method, it automatically moves the "position" of the reading stream (the exact amount depends on the byte size of the type read). So if the binary file has 3 integers written in a row, to read them you would call ReadInt32() three times in a row.

However this also makes reading functions error-prone. What happens if the next bytes of data are a 32-bit integer, and we call ReadDouble for example? A double is 64-bits, so the resulting value would be incorrect. Well fortunately (or unfortunately depending on how you look at it), an "incompatible" read call throws an exception.

Although it might seem a bit of a headache to have exceptions thrown, it is infinitely better than having wrong data read. The latter is much much harder to debug.

For that same reason, it is a good idea in most cases to place the reading routine within a try-catch statement.

A quick side note is that BinaryReader is a wrapper just like BinaryWriter, thus closing a BinaryStream object closes the underlying stream as well.

Conclusion

Writing and reading a binary file is a powerful way to store data outside of a C# application. I encourage you to experiment with it and test it out on your application. Remember that binary file writing and reading is not the only way to handle files in .NET. So test it out to see if it is the best method for your .NET application.

Page 1
<<Writing a Binary File

Back to C# Article List