The problem is this block:
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
When the StreamReader
is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream
is closed. When the StreamWriter
gets closed, it tries to flush everything to the MemoryStream
, but it is closed.
You should consider not putting the StreamReader
in a using block.