C# Append byte array to existing file

2019-01-06 18:08发布

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

5条回答
欢心
2楼-- · 2019-01-06 18:15

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);
    }
}
查看更多
女痞
3楼-- · 2019-01-06 18:15

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.

查看更多
Animai°情兽
4楼-- · 2019-01-06 18:23

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.

查看更多
Ridiculous、
5楼-- · 2019-01-06 18:25

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();
    }
}
查看更多
我想做一个坏孩纸
6楼-- · 2019-01-06 18:29
  1. Create a new FileStream.
  2. Seek() to the end.
  3. Write() the bytes.
  4. Close() the stream.
查看更多
登录 后发表回答