Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Scratch the previous answer - I hadn't noticed that you were using two wrappers around the same stream. That feels somewhat risky to me.</p> <p>Either way, I'd put the <code>StreamWriter</code> and <code>BinaryWriter</code> in their own <code>using</code> blocks.</p> <p>Oh, and yes, it's legal to call <code>ToArray()</code> on the <code>MemoryStream</code> - the data is retained even after it's disposed.</p> <p>If you really want to use the two wrappers, I'd do it like this:</p> <pre><code>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); //&lt;~~ easier to read afterward. normalWriter.Flush(); } } return MemoryStream.ToArray(); } </code></pre> <p>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 <code>StreamWriter</code>'s <a href="http://msdn.microsoft.com/en-us/library/system.io.streamwriter.autoflush.aspx" rel="noreferrer"><code>AutoFlush</code></a> property to true to mitigate the situation, and I <em>believe</em> that <code>BinaryWriter</code> currently doesn't <em>actually</em> require flushing (i.e. it doesn't buffer any data) but relying on that feels risky.</p> <p>If you have to mix binary and text data, I'd use a <code>BinaryWriter</code> and explicitly write the bytes for the string, fetching it with <code>Encoding.GetBytes(string)</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload