MemoryStream - Cannot access a closed Stream
.net, asp.net, c#, memorystream, streamwriter
Solution
This is because the `StreamReader` closes the underlying stream automatically when being disposed of. The `using` statement does this automatically.
However, the `StreamWriter` you're using is still trying to work on the stream (also, the `using` statement for the writer is now trying to dispose of the `StreamWriter`, which is then trying to close the stream).
The best way to fix this is: don't use `using` and don't dispose of the `StreamReader` and `StreamWriter`. See this question.
using (var ms = new MemoryStream())
{
var sw = new StreamWriter(ms);
var sr = new StreamReader(ms);
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
}
If you feel bad about `sw` and `sr` being garbage-collected without being disposed of in your code (as recommended), you could do something like that:
StreamWriter sw = null;
StreamReader sr = null;
try
{
using (var ms = new MemoryStream())
{
sw = new StreamWriter(ms);
sr = new StreamReader(ms);
sw.WriteLine("data");
sw.WriteLine("data 2");
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
}
}
finally
{
if (sw != null) sw.Dispose();
if (sr != null) sr.Dispose();
}
Problem
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 } ```