C# Append byte array to existing file
Solution 1:
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);
}
}
Solution 2:
- Create a new
FileStream
. -
Seek()
to the end. -
Write()
the bytes. -
Close()
the stream.
Solution 3:
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.
Solution 4:
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.