C# Programming > Data

C# Binary File Read and Write

Write Binary Data

A way to store data in C# is to write to a binary file. A binary file allows developers to write data types such as int, bool, string, etc to a file. A binary file can then be read to retrieve those values.

Binary files are useful for saving application settings for example in a settings file. They can also save and load data entered by the user during runtime.

FileStream and BinaryWriter

Before you even start writing code, add the System.IO namespace to the top. All file writing operations come from that .NET namespace. More specifically, you will be using the FileStream and BinaryWriter classes.

FileStream is the class that either creates or opens a file. In the case of writing binary files, you want to use this to create a new file. Of course FileStream has several options when creating files.

BinaryWriter wraps around FileStream and as you can probably guess, it will write to the stream of that file. BinaryWriter is helpful because it allows programmers to write different C# data types to a file without having to worry about the specific bits. For example, a BinaryWriter can write a string or an uint with the same Write function.

To write more complex data structures to a binary file in C#, you have to convert the data structure to a simpler data type supported by the BinaryWriter. Another way is to write a structure of data in simple data type parts.

Here is a very simple code example:

using (FileStream stream = new FileStream("C:\\mysecretfile.txt", FileMode.Create))
{
    using (BinaryWriter writer = new BinaryWriter(stream))
    {
        writer.Write("hello");
        writer.Write(5);
        writer.Close();
    }
}

The source code avoid is pretty simple and does not do much, but it shows some important principles. First off, notice the using statements, these automatically let the developer know that FileStream and BinaryWriter are disposable objects. This way we do not have to explicitly dispose the objects.

Also notice that we still closed the file stream, which is a must whenever working with file or memory streams. But if that is the case, how come stream isn't closed? Take a close look at the code and you will realize that writer wraps around stream. The BinaryWriter stream is the FileStream stream, thus closing writer automatically closes reader.

The last thing to notice is how flexible the Write function is. The function has a ton of overloads to let C# developers directly write a wide range of types into the file. With these basic building blocks, we can write and read some fairly complex files.

Page 2
Reading the Binary File >>

 

Back to C# Article List