ZetCode

C# BinaryReader

last modified November 6, 2026

In this article we show how to read binary data in C# with the BinaryReader class.

BinaryReader from the System.IO namespace reads primitive types from a stream. It is the counterpart of the BinaryWriter class. The reader has a method for each type, such as ReadInt32, ReadDouble, ReadBoolean, and ReadString, and reads multi-byte values in little-endian byte order.

A binary file carries no information about the types of its values. The reader must read the same types in the same order as they were written. Each example in this article therefore writes its data first and then reads it back.

Basic BinaryReader example

The first example reads an integer, a double, a boolean, and a string from a file.

Program.cs
using (var writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
    writer.Write(42);
    writer.Write(3.14);
    writer.Write(true);
    writer.Write("Hello Binary");
}

using var reader = new BinaryReader(File.OpenRead("data.bin"));

int number = reader.ReadInt32();
double pi = reader.ReadDouble();
bool flag = reader.ReadBoolean();
string text = reader.ReadString();

Console.WriteLine($"Int: {number}");
Console.WriteLine($"Double: {pi}");
Console.WriteLine($"Boolean: {flag}");
Console.WriteLine($"String: {text}");

The values are written with a BinaryWriter and read with the matching methods of BinaryReader.

using var reader = new BinaryReader(File.OpenRead("data.bin"));

File.OpenRead opens the file for reading. The using declaration disposes the reader, and with it the stream, at the end of the program.

string text = reader.ReadString();

ReadString reads the length prefix written by BinaryWriter.Write(string) and then the encoded characters.

$ dotnet run
Int: 42
Double: 3.14
Boolean: True
String: Hello Binary

Reading in the wrong order

If the read methods do not match the written data, the reader does not detect it. It interprets the bytes as the requested type.

Program.cs
using (var writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
    writer.Write(42);
    writer.Write(3.14);
}

using var reader = new BinaryReader(File.OpenRead("data.bin"));

long wrong = reader.ReadInt64();
float wrong2 = reader.ReadSingle();

Console.WriteLine(wrong);
Console.WriteLine(wrong2);

We write an integer and a double, but read a long and a float.

long wrong = reader.ReadInt64();
float wrong2 = reader.ReadSingle();

ReadInt64 combines the four bytes of the integer with the first four bytes of the double; ReadSingle reads the remaining four bytes. Both results are meaningless, and no exception is thrown.

$ dotnet run
5902958104789647402
2.1425

Reading arrays

To read an array, the file must say how many elements it contains. The common convention is to write the length before the elements.

Program.cs
int[] numbers = [1, 2, 3, 4, 5];

using (var writer = new BinaryWriter(File.Open("array.bin", FileMode.Create)))
{
    writer.Write(numbers.Length);

    foreach (int n in numbers)
    {
        writer.Write(n);
    }
}

using var reader = new BinaryReader(File.OpenRead("array.bin"));

int length = reader.ReadInt32();
int[] data = new int[length];

for (int i = 0; i < length; i++)
{
    data[i] = reader.ReadInt32();
}

Console.WriteLine($"read {length} values: {string.Join(", ", data)}");

We read the length of the array, allocate it, and fill it in a loop.

int length = reader.ReadInt32();
int[] data = new int[length];

For untrusted files, validate the length before allocating, because a corrupted value could request a huge array.

$ dotnet run
read 5 values: 1, 2, 3, 4, 5

Reading records

This example reads a list of products, each consisting of an integer, a string, a decimal, and a date.

Program.cs
List<Product> products =
[
    new(1001, "Laptop", 999.99m, new DateTime(2026, 3, 15)),
    new(1002, "Mouse", 24.50m, new DateTime(2026, 5, 2)),
    new(1003, "Monitor", 249.00m, new DateTime(2026, 9, 21)),
];

using (var writer = new BinaryWriter(File.Open("products.bin", FileMode.Create)))
{
    writer.Write(products.Count);

    foreach (var p in products)
    {
        writer.Write(p.Id);
        writer.Write(p.Name);
        writer.Write(p.Price);
        writer.Write(p.Added.ToBinary());
    }
}

using var reader = new BinaryReader(File.OpenRead("products.bin"));

int count = reader.ReadInt32();
var loaded = new List<Product>(count);

for (int i = 0; i < count; i++)
{
    int id = reader.ReadInt32();
    string name = reader.ReadString();
    decimal price = reader.ReadDecimal();
    DateTime added = DateTime.FromBinary(reader.ReadInt64());

    loaded.Add(new Product(id, name, price, added));
}

foreach (var p in loaded)
{
    Console.WriteLine($"{p.Id} {p.Name,-8} {p.Price,8:F2} {p.Added:yyyy-MM-dd}");
}

record Product(int Id, string Name, decimal Price, DateTime Added);

The file begins with the number of products, followed by the product records.

decimal price = reader.ReadDecimal();
DateTime added = DateTime.FromBinary(reader.ReadInt64());

ReadDecimal reads 16 bytes. The date was stored with DateTime.ToBinary and is restored with DateTime.FromBinary.

$ dotnet run
1001 Laptop     999.99 2026-03-15
1002 Mouse       24.50 2026-05-02
1003 Monitor    249.00 2026-09-21

Reading until the end of the stream

When the number of values is not stored in the file, we read until the end of the stream.

Program.cs
var rnd = new Random(5);

using (var writer = new BinaryWriter(File.Open("items.bin", FileMode.Create)))
{
    int count = rnd.Next(5, 15);

    for (int i = 0; i < count; i++)
    {
        writer.Write(rnd.Next(100));
    }
}

using var reader = new BinaryReader(File.OpenRead("items.bin"));

var values = new List<int>();

while (reader.BaseStream.Position < reader.BaseStream.Length)
{
    values.Add(reader.ReadInt32());
}

Console.WriteLine($"{values.Count} numbers: {string.Join(" ", values)}");

The writer stores a random number of integers. The fixed seed makes the output reproducible.

while (reader.BaseStream.Position < reader.BaseStream.Length)
{
    values.Add(reader.ReadInt32());
}

The BaseStream property gives access to the underlying stream. We read while its position is before its end. This works for seekable streams such as files and memory streams; for network streams, the length is unknown and the data must carry its own count or end marker.

$ dotnet run
8 numbers: 28 26 62 46 92 14 95 59

String encodings

BinaryReader decodes strings with the encoding passed to its constructor, UTF-8 by default. It must be the same encoding the writer used.

Program.cs
using System.Text;

using (var writer = new BinaryWriter(File.Open("strings.bin", FileMode.Create), Encoding.Unicode))
{
    writer.Write("Žltý kôň");
    writer.Write(Encoding.UTF8.GetBytes("raw UTF-8"));
}

using (var reader = new BinaryReader(File.OpenRead("strings.bin"), Encoding.Unicode))
{
    Console.WriteLine(reader.ReadString());

    byte[] raw = reader.ReadBytes(9);
    Console.WriteLine(Encoding.UTF8.GetString(raw));
}

using (var reader = new BinaryReader(File.OpenRead("strings.bin")))
{
    string wrong = reader.ReadString();
    Console.WriteLine(string.Concat(wrong.Select(Escape)));
}

string Escape(char c) => c < 32 || c > 126 ? $"\\u{(int)c:X4}" : c.ToString();

We write a Slovak text in UTF-16 and raw UTF-8 bytes, and read the file with both the right and the wrong encoding.

using (var reader = new BinaryReader(File.OpenRead("strings.bin"), Encoding.Unicode))

The reader uses the same Encoding.Unicode (UTF-16) as the writer.

byte[] raw = reader.ReadBytes(9);
Console.WriteLine(Encoding.UTF8.GetString(raw));

Raw bytes have no length prefix. We read the known number of bytes and decode them ourselves.

string wrong = reader.ReadString();

The second reader uses the default UTF-8 encoding. The length prefix is read correctly, but the UTF-16 bytes are decoded as UTF-8, which produces control characters and replacement characters (U+FFFD). We print them as escape sequences.

$ dotnet run
Žltý kôň
raw UTF-8
}\u0001l\u0000t\u0000\uFFFD\u0000 \u0000k\u0000\uFFFD\u0000H\u0001

Parsing a header from a MemoryStream

BinaryReader works with any stream. In this example we parse the beginning of a PNG file from a byte array. PNG stores its numbers in big-endian order, so we decode them with BinaryPrimitives.

Program.cs
using System.Buffers.Binary;
using System.Text;

byte[] png =
[
    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A,
    0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x02, 0x58,
    0x08, 0x06, 0x00, 0x00, 0x00,
];

using var reader = new BinaryReader(new MemoryStream(png));

byte[] signature = reader.ReadBytes(8);
Console.WriteLine($"signature: {Convert.ToHexString(signature)}");

int chunkLength = BinaryPrimitives.ReadInt32BigEndian(reader.ReadBytes(4));
string chunkType = Encoding.ASCII.GetString(reader.ReadBytes(4));
Console.WriteLine($"chunk: {chunkType}, {chunkLength} bytes");

int width = BinaryPrimitives.ReadInt32BigEndian(reader.ReadBytes(4));
int height = BinaryPrimitives.ReadInt32BigEndian(reader.ReadBytes(4));
byte bitDepth = reader.ReadByte();
byte colorType = reader.ReadByte();

Console.WriteLine($"{width}x{height}, bit depth {bitDepth}, color type {colorType}");

reader.BaseStream.Position = 16;
Console.WriteLine($"width read as little-endian: {reader.ReadInt32()}");

The bytes contain the PNG signature and the header chunk of an 800x600 image.

int chunkLength = BinaryPrimitives.ReadInt32BigEndian(reader.ReadBytes(4));

We read four raw bytes and decode them as a big-endian integer.

reader.BaseStream.Position = 16;
Console.WriteLine($"width read as little-endian: {reader.ReadInt32()}");

Reading the width with ReadInt32, which assumes little-endian order, gives a wrong value. Setting the Position of the stream moves the reader to any offset.

$ dotnet run
signature: 89504E470D0A1A0A
chunk: IHDR, 13 bytes
800x600, bit depth 8, color type 6
width read as little-endian: 537067520

Reading structs

An array of unmanaged structs can be filled directly from the stream. The MemoryMarshal.AsBytes method views the array as a span of bytes, without unsafe code.

Program.cs
using System.Runtime.InteropServices;

Point3D[] points =
[
    new(1.0f, 2.0f, 3.0f, 0xFF0000),
    new(4.5f, 5.5f, 6.5f, 0x00FF00),
];

using (var writer = new BinaryWriter(File.Open("points.bin", FileMode.Create)))
{
    writer.Write(points.Length);
    writer.Write(MemoryMarshal.AsBytes(points.AsSpan()));
}

using var reader = new BinaryReader(File.OpenRead("points.bin"));

int count = reader.ReadInt32();
var loaded = new Point3D[count];

reader.BaseStream.ReadExactly(MemoryMarshal.AsBytes(loaded.AsSpan()));

foreach (var p in loaded)
{
    Console.WriteLine($"{p} color #{p.Color:X6}");
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
record struct Point3D(float X, float Y, float Z, int Color);

We write two 3D points and read them back in a single call.

reader.BaseStream.ReadExactly(MemoryMarshal.AsBytes(loaded.AsSpan()));

The ReadExactly method fills the whole span or throws an EndOfStreamException. It is called on the stream, since the reader has already consumed the count.

[StructLayout(LayoutKind.Sequential, Pack = 1)]
record struct Point3D(float X, float Y, float Z, int Color);

The struct must have the same layout as when it was written. This technique is fast, but the data depends on the byte order of the machine.

$ dotnet run
Point3D { X = 1, Y = 2, Z = 3, Color = 16711680 } color #FF0000
Point3D { X = 4.5, Y = 5.5, Z = 6.5, Color = 65280 } color #00FF00

Handling truncated data

Reading past the end of the stream throws an EndOfStreamException. We can check the remaining bytes before reading, or catch the exception.

Program.cs
using (var writer = new BinaryWriter(File.Open("partial.bin", FileMode.Create)))
{
    writer.Write(42);
    writer.Write("Incomplete");
    writer.Write((short)7);
}

using var reader = new BinaryReader(File.OpenRead("partial.bin"));

int number = reader.ReadInt32();
string text = reader.ReadString();

Console.WriteLine($"Int: {number}, String: {text}");

long remaining = reader.BaseStream.Length - reader.BaseStream.Position;
Console.WriteLine($"{remaining} bytes remaining");

if (remaining >= sizeof(double))
{
    Console.WriteLine(reader.ReadDouble());
}
else
{
    Console.WriteLine("not enough data for a double");
}

try
{
    double value = reader.ReadDouble();
}
catch (EndOfStreamException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

reader.BaseStream.Position = 4;
Console.WriteLine($"ReadBytes(100) returned {reader.ReadBytes(100).Length} bytes");

The file contains an integer, a string, and a short, but we try to read a double after the string.

if (remaining >= sizeof(double))

Only two bytes remain, so the check prevents the read.

catch (EndOfStreamException e)

ReadDouble throws because eight bytes are not available.

Console.WriteLine($"ReadBytes(100) returned {reader.ReadBytes(100).Length} bytes");

Unlike the typed methods, ReadBytes does not throw at the end of the stream. It returns fewer bytes than requested, so check the length of the result.

$ dotnet run
Int: 42, String: Incomplete
2 bytes remaining
not enough data for a double
EndOfStreamException: Unable to read beyond the end of the stream.
ReadBytes(100) returned 13 bytes

Source

BinaryReader class

In this article we have read binary data in C# with BinaryReader.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.