I have a file with size 10124, I am adding a byte array, which has length 4 in the beginning of the file. After that the file size should become 10128, but as I write it to file, the size decreased to 22 bytes. I don't know where is the problem
public void AppendAllBytes(string path, byte[] bytes)
{
var encryptedFile = new FileStream(path, FileMode.Open, FileAccess.Read);
////argument-checking here.
Stream header = new MemoryStream(bytes);
var result = new MemoryStream();
header.CopyTo(result);
encryptedFile.CopyTo(result);
using (var writer = new StreamWriter(@"C:\\Users\\life.monkey\\Desktop\\B\\New folder (2)\\aaaaaaaaaaaaaaaaaaaaaaaaaaa.docx.aef"))
{
writer.Write(result);
}
}
How can I write bytes to the file?
The issue seems to be caused by:
using a
StreamWriter
to write binary formatted data. The name does not inthuitively suggest this, but theStreamWriter
class is suited for writing textual data.passing an entire stream instead of the actual binary data. To obtain the bytes stored in a
MemoryStream
, use its convenientToArray()
method.I suggest you the following code:
The code above uses the
BinaryWriter
class which is better suited for binary data. It has aWrite(byte[] bytes)
method overload that is used above to write an entire array to the file. The code uses regular calls to theFlush()
method that some may consider not needed, but these guarantee in general, that all the data written prior the call of theFlush()
method is persisted within the stream.