C# Append byte array to existing file

user725913 picture user725913 · Jul 28, 2011 · Viewed 48.2k times · Source

I would like to append a byte array to an already existing file (C:\test.exe). Assume the following byte array:

byte[] appendMe = new byte[ 1000 ] ;

File.AppendAllBytes(@"C:\test.exe", appendMe); // Something like this - Yes, I know this method does not really exist.

I would do this using File.WriteAllBytes, but I am going to be using an ENORMOUS byte array, and System.MemoryOverload exception is constantly being thrown. So, I will most likely have to split the large array up into pieces and append each byte array to the end of the file.

Thank you,

Evan

Answer

Ani picture Ani · Jul 28, 2011

One way would be to create a FileStream with the FileMode.Append creation mode.

Opens the file if it exists and seeks to the end of the file, or creates a new file.

This would look something like:

public static void AppendAllBytes(string path, byte[] bytes)
{
    //argument-checking here.

    using (var stream = new FileStream(path, FileMode.Append))
    {
        stream.Write(bytes, 0, bytes.Length);
    }
}