Just read the file without ever decoding the bytes. And you have to choose an encoding for your header - ASCII seems to be the safest choice in your situation.
const String fileName = "test.file";
const String header = "MyHeader";
var headerBytes = Encoding.ASCII.GetBytes(header);
var fileContent = File.ReadAllBytes(fileName);
using (var stream = File.OpenWrite(fileName))
{
stream.Write(headerBytes, 0, headerBytes.Length);
stream.Write(fileContent, 0, fileContent.Length);
}
Note that the code directly operates on the stream and does not use a TextReader
or TextWriter
(this are the abstract base classes of StreamReader
and StreamWriter
). You can use a BinaryReader
and BinaryWriter
to simplify accessing the stream if you have to deal with tasks complexer then just reading and writing array.