24 June 2025

.NET - Read/write a binary file line by line

To read a text file, you can use a StreamReader, but to read a binary file, you need a BinaryReader.This is how you use it:

if (File.Exists(FILENAME))
{
    using (var stream = new FileStream(FILENAME, FileMode.Open))
    using (var reader = new BinaryReader(stream))
    {
        if (stream.Length <= 0) return; //The file is empty.
        int i = reader.ReadInt32();
        string s = reader.ReadString();
    }
}

Writing is similar:

using (var stream = new FileStream(SaveFilePath, FileMode.Create))
using (var writer = new BinaryWriter(stream))
{
    writer.Write(305);
    writer.Write("EGS");
}

The file will be automatically created if it doesn't exist yet.