C# Append byte array to existing file
Asked Answered
A

6

55

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

Aerography answered 28/7, 2011 at 16:29 Comment(4)
I don't understand the problem.Huynh
My main goal is to add two enormous byte arrays together. This is not possible, however, as an exception (out of memory) is thrown. So, my solution is to write each byte array to an output file separately, (as opposed to combining them and writing them to the file as one).Aerography
You should at least provide some code that you've tried... So far it is unclear what is causing your problem - all Stream and Writer classes are able to write byte arrays directly.Useless
What is so difficult to understand about "append a byte array to an already existing file" ? Everyone else seemed to understand it...Aerography
U
93

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);
    }
}
Undermine answered 28/7, 2011 at 16:36 Comment(3)
This looks perfect. Some other answers use BinaryWriter; why would one choose this over the FileStream method? I'm guessing it performs exactly the same function, but takes more lines of code.Paviour
does it need to flush?Abase
@JohnDemetriou after you get out of the block from the using statement, Close() gets called, which will in turn will call Flush(); so I don't think you need to call Flush()Free
S
7
  1. Create a new FileStream.
  2. Seek() to the end.
  3. Write() the bytes.
  4. Close() the stream.
Shore answered 28/7, 2011 at 16:34 Comment(1)
This seems to be the best solution to my problem. I'll give it a go and let you know. ThanksAerography
G
6

You can also use the built-in FileSystem.WriteAllBytes Method (String, Byte[], Boolean).

public static void WriteAllBytes(
    string file,
    byte[] data,
    bool append
)

Set append to True to append to the file contents; False to overwrite the file contents. Default is False.

Gustavo answered 6/10, 2015 at 13:57 Comment(1)
As far as I can tell this is a VB.Net only solution. msdn.microsoft.com/en-us/library/…Dearborn
P
3

I'm not exactly sure what the question is, but C# has a BinaryWriter method that takes an array of bytes.

BinaryWriter(Byte[])

bool writeFinished = false;
string fileName = "C:\\test.exe";
FileStream fs = new FileString(fileName);
BinaryWriter bw = new BinaryWriter(fs);
int pos = fs.Length;
while(!writeFinished)
{
   byte[] data = GetData();
   bw.Write(data, pos, data.Length);
   pos += data.Length;
}

Where writeFinished is true when all the data has been appended, and GetData() returns an array of data to be appended.

Psychokinesis answered 28/7, 2011 at 16:33 Comment(0)
D
0

you can simply create a function to do this

public static void AppendToFile(string fileToWrite, byte[] DT)
{
    using (FileStream FS = new FileStream(fileToWrite, File.Exists(fileToWrite) ? FileMode.Append : FileMode.OpenOrCreate, FileAccess.Write)) {
        FS.Write(DT, 0, DT.Length);
        FS.Close();
    }
}
Drue answered 16/2, 2016 at 5:42 Comment(1)
using{} does not need calling FS.Close();Activist
R
0

An alternative approach using MemoryStream:

public static byte[] GetLargeBytes(byte[] bytes)
{
    using (var stream = new MemoryStream(new byte[1024 * 1024 * 10], true))
    {
        stream.Write(bytes);
        stream.Position = 0;
        return stream.ToArray();
    }
}
Rienzi answered 1/3 at 22:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.