Why using (var sw = new StreamWriter(ms)) returns Cannot access a closed Stream exception while the MemoryStream is on top of this code?
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms))
{
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
using (var sr = new StreamReader(ms))
{
Console.WriteLine(sr.ReadToEnd());
}
} //error here
}
This is because the
StreamReadercloses the underlying stream automatically when being disposed of. Theusingstatement does this automatically.However, the
StreamWriteryou’re using is still trying to work on the stream (also, theusingstatement for the writer is now trying to dispose of theStreamWriter, which is then trying to close the stream).The best way to fix this is: don’t use
usingand don’t dispose of theStreamReaderandStreamWriter. See this question.If you feel bad about
swandsrbeing garbage-collected without being disposed of in your code (as recommended), you could do something like that: