Appending a binary file in C#

To add bytes to the end of a binary file, this is the basic code needed:

byte[] bytes = new byte[] { 1, 2, 3, 4, 5 };
using FileStream fileStream = new(FULL_FILE_NAME, FileMode.Append);
fileStream.Write(bytes, 0, bytes.Length);

If you’re potentially bringing in a lot of data, make sure you use a stream for the incoming data and write a little at a time.

For a small amount of data, you can use a ReadOnlySpan<byte> instead of a byte array, to avoid the object allocation on the array:

ReadOnlySpan<byte> bytes = stackalloc byte[] { 1, 2, 3, 4, 5 };
using FileStream fileStream = new(FULL_FILE_NAME, FileMode.Append);
fileStream.Write(bytes);

For whatever reason, there is no File.AppendAllBytes – there’s a helper method for writing or appending text, and for writing bytes, but not for appending bytes.

If you want to write other types, rather than having to manually convert to bytes, you can wrap your stream with a BinaryWriter, and write lots of different types, letting the framework handle converting to bytes – check the Intellisense for the various overloads for more details:

using FileStream fileStream = new(FULL_FILE_NAME, FileMode.Append);
using BinaryWriter binaryWriter = new(fileStream);

const string MESSAGE = "hello world";

binaryWriter.Write(MESSAGE);

Leave a Reply

Your email address will not be published.