Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Three things:</p> <ul> <li>Don't close the <code>StreamWriter</code>. That will close the <code>MemoryStream</code>. You do need to flush the writer though.</li> <li>Reset the position of the stream before reading.</li> <li>If you're going to write directly to the stream, you need to flush the writer first.</li> </ul> <p>So:</p> <pre><code>using (var stream = new MemoryStream()) { var sw = new StreamWriter(stream); sw.Write("{"); foreach (var kvp in keysAndValues) { sw.Write("'{0}':", kvp.Key); sw.Flush(); ser.WriteObject(stream, kvp.Value); } sw.Write("}"); sw.Flush(); stream.Position = 0; using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } </code></pre> <p>There's another simpler alternative though. All you're doing with the stream when reading is converting it into a string. You can do that more simply:</p> <pre><code>return Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int) stream.Length); </code></pre> <p>Unfortunately <code>MemoryStream.Length</code> will throw if the stream has been closed, so you'd probably want to call the <code>StreamWriter</code> constructor that doesn't close the underlying stream, or just don't close the <code>StreamWriter</code>.</p> <p>I'm concerned by you writing directly to the the stream - what is <code>ser</code>? Is it an XML serializer, or a binary one? If it's binary, your model is somewhat flawed - you shouldn't mix binary and text data without being very careful about it. If it's XML, you may find that you end up with byte-order marks in the middle of your string, which could be problematic.</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