tags:

views:

259

answers:

3

I have a binary file to which I want to append a chunk of data at the end of the file, how can I achieve this using C# and .net? also are there any considerations to take when writing to the end of a binary file? thanks a lot for your help.

+1  A: 

Use File.OpenWrite in conjunction with Stream.Write.

using (Stream file = File.OpenWrite(@"C:\path\to\somefile.bin"))
{
    file.Write(someBytes, 0, someBytes.Length);
}

However, there are considerations to think about when appending to a binary file. Typically, binary files are taken as a whole. To append data to a binary file could destroy the ability for applications that rely on this data to access the information after you've appended your data to the same file. I'd recommend not appending the data to an existing file, but instead to add the data to it's own new file. This will make it far easier to use the data.

David Morton
+5  A: 
private static void AppendData(string filename, int intData, string stringData, byte[] lotsOfData)
{
    using (Stream fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None))
    {
        using (BinaryWriter bw = new BinaryWriter(fileStream))
        {
            bw.Write(intData);
            bw.Write(stringData);
            bw.Write(lotsOfData);
        }
    }
}
Jesse C. Slicer
+1 I like this answer because it shows you how to additionally shove native data types into the stream as binary representations.
John K
@jdk - which of course makes a *lot* of presumptions about what the underlying data *is*; a `byte[]` sure, that would always make sense... but the encoding for the others could be *miles* out.
Marc Gravell
+1 for the binary writer, if you are writing binary data it is always best to use the writer
Grant Peters
+2  A: 

You should be able to do this via the Stream:

using (FileStream data = new FileStream(path, FileMode.Append))
{
    data.Write(...);
}

As for considerations - the main one would be: does the underlying data format support append? Many don't, unless it is your own raw data, or text etc. A well-formed xml document doesn't support append (without considering the final end-element), for example. Nor will something like a Word document. Some do, however. So; is your data OK with this...

Marc Gravell