Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The BinaryReader and BinaryWriter classes

Reference for BinaryReader and BinaryWriter in C#: write and read ints, doubles, strings and bytes in binary, string length prefix, endianness, EOF errors, leaveOpen.

BinaryWriter writes .NET primitive values (int, double, bool, string, byte[], and so on) to a Stream in a compact binary form. BinaryReader reads them back with matching methods: ReadInt32, ReadDouble, ReadString. They are a simple way to store records in your own file format, to build protocol messages, or to parse a fixed layout without calling BitConverter for every field.

There is no type information in the output. The reader must call the same methods, in the same order, as the writer used. Numbers are written in little-endian byte order and strings carry a length prefix, so the files are readable on any platform by other .NET programs but are not a general-purpose interchange format.

C#
using var writer = new BinaryWriter(File.Create("data.bin"));
writer.Write(42);
writer.Write("hello");

Try it

C# Write a record and read it back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Byte layout, endianness and bad data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public BinaryWriter(Stream output);
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen = false);
public BinaryReader(Stream input);
public BinaryReader(Stream input, Encoding encoding, bool leaveOpen = false);
Writer method Reader method Bytes on the stream
Write(bool) ReadBoolean() 1 (0 or 1)
Write(byte), Write(sbyte) ReadByte(), ReadSByte() 1
Write(short), Write(ushort) ReadInt16(), ReadUInt16() 2
Write(int), Write(uint) ReadInt32(), ReadUInt32() 4
Write(long), Write(ulong) ReadInt64(), ReadUInt64() 8
Write(float), Write(double) ReadSingle(), ReadDouble() 4, 8
Write(decimal) ReadDecimal() 16
Write(char) ReadChar() 1 to 4 (encoded)
Write(string) ReadString() length prefix (7-bit encoded) + encoded characters
Write(byte[]) ReadBytes(count) the bytes, no length prefix
Write7BitEncodedInt(int) Read7BitEncodedInt() 1 to 5, variable

Also available: BaseStream, Flush(), Seek(...) on the writer, PeekChar() and Read(...) on the reader. Newer versions add Half, Int128 and UInt128 support.

Errors: EndOfStreamException when the stream ends inside a value, IOException for corrupt string lengths and I/O failures, ObjectDisposedException after disposal, ArgumentException when the stream does not support reading or writing.

Usage notes

  • Order and types must match. Writing an int and reading a long gives garbage and an EndOfStreamException later. Keep one function that writes a record and one that reads it, next to each other.
  • Write(byte[]) has no length. Write the count yourself (Write(bytes.Length)) before the data, then read it back with ReadBytes(count).
  • ReadBytes(n) can return fewer bytes at the end of the stream; check the length of the result. The fixed-size primitive readers throw EndOfStreamException instead.
  • Endianness. BinaryWriter and BinaryReader always use little-endian. Network protocols and many file formats use big-endian; use BinaryPrimitives on spans for those.
  • Strings. The default encoding is UTF-8 and the length prefix counts bytes, not characters. Use Write(char[]) or an encoding of your choice when the format needs fixed-width text.
  • Disposing closes the stream. Pass leaveOpen: true to keep using the underlying stream, and flush the writer before reading the stream back.
  • Versioning. Write a magic number and a version at the start of files. The format has no schema, so old readers cannot skip unknown fields.
  • Not for untrusted data. A hostile file can contain a negative or enormous length. ReadString rejects negative prefixes and fails at the end of the data, but lengths you read yourself and pass to ReadBytes(count) or use in a loop must be checked against a sensible maximum first.
  • Alternatives. Use System.Text.Json for readable data, BitConverter and BinaryPrimitives for low-level control, and a serialization library when you need cross-language formats. BinaryFormatter is removed and must not be used.