Suppose this C# code:
using (MemoryStream stream = new MemoryStream())
{
StreamWriter normalWriter = new StreamWriter(stream);
BinaryWriter binaryWriter = new BinaryWriter(stream);
foreach(...)
{
binaryWriter.Write(number);
normalWriter.WriteLine(name); //<~~ easier to reader afterward.
}
return MemoryStream.ToArray();
}
My questions are:
- Do I need to use flush inside the
loop to preserve order? - Is returning
MemoryStream.ToArray()legal? I using theusing-block as a convention, I’m afraid it will mess things up.
Scratch the previous answer – I hadn’t noticed that you were using two wrappers around the same stream. That feels somewhat risky to me.
Either way, I’d put the
StreamWriterandBinaryWriterin their ownusingblocks.Oh, and yes, it’s legal to call
ToArray()on theMemoryStream– the data is retained even after it’s disposed.If you really want to use the two wrappers, I’d do it like this:
I have to say, I’m somewhat wary of using two wrappers around the same stream though. You’ll have to keep flushing each of them after each operation to make sure you don’t end up with odd data. You could set the
StreamWriter‘sAutoFlushproperty to true to mitigate the situation, and I believe thatBinaryWritercurrently doesn’t actually require flushing (i.e. it doesn’t buffer any data) but relying on that feels risky.If you have to mix binary and text data, I’d use a
BinaryWriterand explicitly write the bytes for the string, fetching it withEncoding.GetBytes(string).