简体   繁体   English

C# 将字节数组附加到现有文件

[英]C# Append byte array to existing file

I would like to append a byte array to an already existing file (C:\\test.exe) .我想将一个字节数组附加到一个已经存在的文件(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.我会使用 File.WriteAllBytes 来做到这一点,但我将使用一个巨大的字节数组,并且不断抛出 System.MemoryOverload 异常。 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埃文

One way would be to create a FileStream with theFileMode.Append creation mode.一种方法是使用FileMode.Append创建模式创建FileStream

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);
    }
}
  1. Create a new FileStream .创建一个新的FileStream
  2. Seek() to the end. Seek()到最后。
  3. Write() the bytes. Write()字节。
  4. Close() the stream. Close()流。

You can also use the built-in FileSystem.WriteAllBytes Method (String, Byte[], Boolean) .您还可以使用内置的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;将 append 设置为True以附加到文件内容; False to overwrite the file contents. False覆盖文件内容。 Default is False.默认值为假。

I'm not exactly sure what the question is, but C# has a BinaryWriter method that takes an array of bytes.我不确定问题是什么,但 C# 有一个BinaryWriter方法,它接受一个字节数组。

BinaryWriter(Byte[]) BinaryWriter(字节[])

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.当所有数据都已附加时, writeFinished为真, GetData()返回要附加的数据数组。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM