Writing to a binary file in C#

Here are the basic ways of writing bytes to a file. Both of these will create a new file, or overwrite if the file alread exists. Both of these are useful depending on your situation.

/// <summary>
/// When you have an array of bytes.
/// </summary>
void ByteArray()
{
    byte[] fileBytes = { 1, 2, 3, 4, 5 };
    File.WriteAllBytes(FULL_FILE_NAME, fileBytes);
}

/// <summary>
/// When you're writing from another stream. Grab a buffer of bytes and write
/// it a little at a time.
/// </summary>
void BytesFromOtherStream()
{
    const int BUFFER_LENGTH = 0x4000;
    byte[] buffer = new byte[BUFFER_LENGTH];
    using FileStream inputStream = File.OpenRead(SOURCE_FULL_FILE_NAME);
    using FileStream fileStream = File.Create(FULL_FILE_NAME);

    int count;
    while ((count = inputStream.Read(buffer, 0, BUFFER_LENGTH)) > 0)
    {
        fileStream.Write(buffer, 0, count);
    }
}

Leave a Reply

Your email address will not be published.