C# BinaryWriter
last modified November 6, 2026
In this article we show how to write binary data in C# with the
BinaryWriter class.
BinaryWriter from the System.IO namespace writes
primitive types as binary values to a stream. Numbers are stored in their
in-memory form instead of as text, so the files are compact and fast to read.
The data is read back with the
BinaryReader class, in the same order and with the same types.
The writer has an overloaded Write method for bool,
all integer types, float, double,
decimal, Half, char,
string, byte arrays, and spans. Multi-byte values are always
written in little-endian byte order, regardless of the processor.
Basic BinaryWriter example
The first example writes four values of different types to a file and shows the bytes that were written.
using (var writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
{
writer.Write(42);
writer.Write(3.14159);
writer.Write(true);
writer.Write("Hello");
}
byte[] bytes = File.ReadAllBytes("data.bin");
Console.WriteLine($"{bytes.Length} bytes");
Console.WriteLine(Convert.ToHexString(bytes.AsSpan(0, 4)));
Console.WriteLine(Convert.ToHexString(bytes.AsSpan(4, 8)));
Console.WriteLine(Convert.ToHexString(bytes.AsSpan(12, 1)));
Console.WriteLine(Convert.ToHexString(bytes.AsSpan(13)));
We write an integer, a double, a boolean, and a string. Then we read the whole file and print its parts in hexadecimal.
using (var writer = new BinaryWriter(File.Open("data.bin", FileMode.Create)))
The writer wraps a FileStream. FileMode.Create
creates a new file or overwrites an existing one. Disposing the writer at the
end of the using block flushes the data and closes the
stream.
Console.WriteLine(Convert.ToHexString(bytes.AsSpan(0, 4)));
The integer 42 occupies four bytes. The least significant byte
2A comes first. The double takes eight bytes in the IEEE 754
format, and the boolean one byte.
Console.WriteLine(Convert.ToHexString(bytes.AsSpan(13)));
A string is prefixed with its length in bytes, here 5, followed by the UTF-8 encoded characters. The file has 4 + 8 + 1 + 6 = 19 bytes.
$ dotnet run 19 bytes 2A000000 6E861BF0F9210940 01 0548656C6C6F
Strings and encodings
Write(string) writes the length of the encoded string as a
7-bit encoded integer, followed by the bytes. Small lengths take one
byte; each byte holds seven bits of the number, and the high bit signals that
another byte follows. The encoding is UTF-8 unless another one is passed to the
constructor.
using System.Text;
var ms = new MemoryStream();
using (var writer = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true))
{
writer.Write("čaj");
writer.Write("čaj".ToCharArray());
writer.Write(new string('a', 200));
}
byte[] data = ms.ToArray();
Console.WriteLine(Convert.ToHexString(data.AsSpan(0, 5)));
Console.WriteLine(Convert.ToHexString(data.AsSpan(5, 4)));
Console.WriteLine(Convert.ToHexString(data.AsSpan(9, 3)));
Console.WriteLine($"total: {data.Length} bytes");
ms.SetLength(0);
using (var writer = new BinaryWriter(ms, Encoding.Unicode))
{
writer.Write("čaj");
Console.WriteLine(Convert.ToHexString(ms.ToArray()));
}
We write a string with a non-ASCII character, the same text as a character array, and a long string. Then we write the text in UTF-16.
using (var writer = new BinaryWriter(ms, Encoding.UTF8, leaveOpen: true))
The leaveOpen parameter keeps the memory stream open after the
writer is disposed, so we can reuse it.
writer.Write("čaj".ToCharArray());
A character array is encoded without a length prefix. The reader must know how many characters to read.
writer.Write(new string('a', 200));
The length 200 does not fit into seven bits, so the prefix takes two bytes:
C8 01.
using (var writer = new BinaryWriter(ms, Encoding.Unicode))
With UTF-16, each of the three characters takes two bytes and the prefix is 6. The reader must use the same encoding as the writer.
$ dotnet run 04C48D616A C48D616A C80161 total: 211 bytes 060D0161006A00
Writing arrays
There is no method for writing an array of integers. We write the number of elements first, followed by the elements, so the reader knows how many to read.
int[] numbers = [10, 20, 30, 40, 50];
double[] temps = [21.5, 22.1, 19.8];
using (var writer = new BinaryWriter(File.Open("arrays.bin", FileMode.Create)))
{
writer.Write(numbers.Length);
foreach (int n in numbers)
{
writer.Write(n);
}
writer.Write7BitEncodedInt(temps.Length);
foreach (double t in temps)
{
writer.Write(t);
}
}
Console.WriteLine($"file size: {new FileInfo("arrays.bin").Length} bytes");
Console.WriteLine(Convert.ToHexString(File.ReadAllBytes("arrays.bin").AsSpan(0, 12)));
We write an array of integers and an array of doubles.
writer.Write(numbers.Length);
The length is written as a four-byte integer.
writer.Write7BitEncodedInt(temps.Length);
The Write7BitEncodedInt method writes the length in the same
compact format that is used for string prefixes. Lengths below 128 take a
single byte.
$ dotnet run file size: 49 bytes 050000000A00000014000000
Writing records
A binary file often contains a sequence of records with mixed types.
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());
}
}
Console.WriteLine($"wrote {products.Count} products, {new FileInfo("products.bin").Length} bytes");
record Product(int Id, string Name, decimal Price, DateTime Added);
We write a list of products, preceded by their number.
writer.Write(p.Price); writer.Write(p.Added.ToBinary());
A decimal is written as 16 bytes. DateTime has no
Write overload; the ToBinary method converts it to a
long that preserves the ticks and the kind of the date.
$ dotnet run wrote 3 products, 109 bytes
Writing to a MemoryStream
BinaryWriter writes to any stream. A MemoryStream
collects the bytes in memory, which is useful for building network messages
or binary payloads.
using var ms = new MemoryStream();
using var writer = new BinaryWriter(ms);
writer.Write((byte)1);
writer.Write((short)-2);
writer.Write(1.5f);
writer.Write((ushort)0xCAFE);
writer.Write([0xDE, 0xAD]);
writer.Flush();
byte[] data = ms.ToArray();
Console.WriteLine($"{data.Length} bytes: {BitConverter.ToString(data)}");
We write values of various sizes and print the resulting bytes.
writer.Write((byte)1); writer.Write((short)-2);
The cast selects the overload and thus the number of bytes. The short value -2
is stored in two's complement as FE FF.
writer.Flush();
Flush pushes all buffered data to the underlying stream before
we read it with ToArray.
$ dotnet run 11 bytes: 01-FE-FF-00-00-C0-3F-FE-CA-DE-AD
Seeking and patching a header
Some formats store a count or a size in a header that is known only after the data is written. With a seekable stream, we write a placeholder, write the data, and then go back to fill in the value.
string[] lines = ["first entry", "second entry", "third entry"];
using (var stream = new FileStream("log.bin", FileMode.Create))
using (var writer = new BinaryWriter(stream))
{
writer.Write("LOG1"u8);
long countPos = stream.Position;
writer.Write(0);
int count = 0;
foreach (string line in lines)
{
writer.Write(line);
count++;
}
stream.Seek(countPos, SeekOrigin.Begin);
writer.Write(count);
stream.Seek(0, SeekOrigin.End);
}
byte[] head = File.ReadAllBytes("log.bin")[..8];
Console.WriteLine(BitConverter.ToString(head));
We write a small log file with a four-byte signature and the number of entries.
writer.Write("LOG1"u8);
The u8 suffix creates a UTF-8 byte span. It is written as raw
bytes without a length prefix, which is the usual way to write a file
signature.
stream.Seek(countPos, SeekOrigin.Begin); writer.Write(count);
We remember the position of the placeholder, return to it, and overwrite it with the real count.
$ dotnet run 4C-4F-47-31-03-00-00-00
Byte order
BinaryWriter always uses little-endian byte order. Network
protocols and many file formats, such as PNG, use big-endian order. The
BinaryPrimitives class writes values in either order.
using System.Buffers.Binary;
int value = 0x12345678;
var ms = new MemoryStream();
using (var writer = new BinaryWriter(ms))
{
writer.Write(value);
Span<byte> buf = stackalloc byte[4];
BinaryPrimitives.WriteInt32BigEndian(buf, value);
writer.Write(buf);
}
byte[] data = ms.ToArray();
Console.WriteLine($"little-endian: {Convert.ToHexString(data, 0, 4)}");
Console.WriteLine($"big-endian: {Convert.ToHexString(data, 4, 4)}");
Console.WriteLine($"this machine is little-endian: {BitConverter.IsLittleEndian}");
We write the same integer in both byte orders.
Span<byte> buf = stackalloc byte[4]; BinaryPrimitives.WriteInt32BigEndian(buf, value); writer.Write(buf);
The value is encoded into a stack-allocated buffer, which is then written as raw bytes.
$ dotnet run little-endian: 78563412 big-endian: 12345678 this machine is little-endian: True
Writing structs
An array of structs that contain only unmanaged fields can be written in one
call. The MemoryMarshal.AsBytes method views the elements as
bytes, without copying and without unsafe code.
using System.Runtime.InteropServices;
Point3D[] points =
[
new(1.0f, 2.0f, 3.0f, 0xFF0000),
new(4.5f, 5.5f, 6.5f, 0x00FF00),
];
Console.WriteLine($"struct size: {Marshal.SizeOf<Point3D>()} bytes");
using (var writer = new BinaryWriter(File.Open("points.bin", FileMode.Create)))
{
writer.Write(points.Length);
writer.Write(MemoryMarshal.AsBytes(points.AsSpan()));
}
byte[] data = File.ReadAllBytes("points.bin");
Console.WriteLine($"file size: {data.Length} bytes");
Console.WriteLine(Convert.ToHexString(data.AsSpan(4, 16)));
[StructLayout(LayoutKind.Sequential, Pack = 1)]
record struct Point3D(float X, float Y, float Z, int Color);
We write an array of 3D points with a color.
[StructLayout(LayoutKind.Sequential, Pack = 1)] record struct Point3D(float X, float Y, float Z, int Color);
The StructLayout attribute keeps the fields in declaration order
without padding, so a point takes exactly 16 bytes.
writer.Write(MemoryMarshal.AsBytes(points.AsSpan()));
The whole array is written as 32 bytes. The resulting layout depends on the byte order of the machine, so this technique is suitable for local files and interop, not for portable formats.
$ dotnet run struct size: 16 bytes file size: 36 bytes 0000803F00000040000040400000FF00
Source
In this article we have written binary data in C# with
BinaryWriter.
Author
List all C# tutorials.