I’ll leave my original question below. My question is why does the following lines produce an exception
(you can see it run at http://www.ideone.com/rfQLE)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace CSQuick
{
class Program
{
static void Main(string[] args)
{
using (var ff = new MemoryStream())
using (var f = new StreamWriter(ff))
{
f.WriteLine("Hi");
using (TextReader ts = new StreamReader(ff))
{
}
}
}
}
}
Exception from ideone website (possibly using mono? I am running MSVS 2010 C# which causes an exception)
Unhandled Exception: System.ObjectDisposedException: The object was used after being disposed.
at System.IO.MemoryStream.CheckIfClosedThrowDisposed () [0x00000] in <filename unknown>:0
at System.IO.MemoryStream.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at System.IO.StreamWriter.FlushBytes () [0x00000] in <filename unknown>:0
at System.IO.StreamWriter.Flush () [0x00000] in <filename unknown>:0
at System.IO.StreamWriter.Dispose (Boolean disposing) [0x00000] in <filename unknown>:0
Why am i getting a exception with the msg “Cannot access a closed Stream.” ? What i like to do is use a streamwriter to write text and store the final results in temp. The below should do that but i dont understand how or why my stream is closed?
using (var ff = new MemoryStream())
using (var f = new StreamWriter(ff))
{
foreach (var t in blah)
{
blahblah(t, f);
}
ff.Flush()
using (TextReader ts = new StreamReader(ff))
{
temp = ts.ReadToEnd();
do_a_check(fn, temp);
}
}//Cannot access a closed Stream.
What is happening is that when you dispose the TextReader, the resources within it is disposed as well (the MemoryStream). So when the StreamWriter is disposed, it flushes, thus writing to the disposed MemoryStream.
Your small repro code could be changed to flush:
Or you can set
AutoFlushwhich will cause the stream to be flushed each write, then this exception won’t be present if you do not put a write line after disposing: