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:
MemoryStream.ToArray()
legal? I using the using
-block as a convention, I'm afraid it will mess things up.Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
You don't need to use Flush on the MemoryStream , as it's not buffering anything that is written to any other source. There is simply nothing to flush anywhere. The Flush method is only present in the MemoryStream object because it inherits from the Stream class.
StreamWriter(String, Boolean) Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to.
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 StreamWriter
and BinaryWriter
in their own using
blocks.
Oh, and yes, it's legal to call ToArray()
on the MemoryStream
- the data is retained even after it's disposed.
If you really want to use the two wrappers, I'd do it like this:
using (MemoryStream stream = new MemoryStream()) { using (StreamWriter normalWriter = new StreamWriter(stream)) using (BinaryWriter binaryWriter = new BinaryWriter(stream)) { foreach(...) { binaryWriter.Write(number); binaryWriter.Flush(); normalWriter.WriteLine(name); //<~~ easier to read afterward. normalWriter.Flush(); } } return MemoryStream.ToArray(); }
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
's AutoFlush
property to true to mitigate the situation, and I believe that BinaryWriter
currently 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 BinaryWriter
and explicitly write the bytes for the string, fetching it with Encoding.GetBytes(string)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With