I need to create a file where some parts are strings (utf-8), while some parts are bytes.
I tinkered for hours with StreamWriter
and BinaryWriter
, but this is the only thing that works:
using (var stream = new FileStream(_caminho, FileMode.Create, FileAccess.Write))
{
using (var writer = new StreamWriter(stream))
{
writer.Write(myString);
}
}
using (var stream = new FileStream(_caminho, FileMode.Append, FileAccess.Write))
{
using (var writer = new BinaryWriter(stream))
{
writer.Write(oneSingleByte);
}
}
The problem is that I have to close the FileStream and open another one just to write a single byte, because either the BinaryStream.Write(string)
method prepends a "length" field (undesired in my case) or the StreamWriter.Write(byte)
encodes the byte value instead of actually writing directly.
My question is: is there another class I can use so that I can create the FileStream only once, and write my string and my byte one after another?