Memorystream - Cannot Access a Closed Stream

MemoryStream - Cannot access a closed Stream

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();
}

getting an error like Cannot access a closed Stream while trying to download word

You're returning mem from inside your using at which point it is disposed.

The "mem" variable inside this File() goes out of scope and is disposed as soon as you return it.

return File(mem, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");

E.g., in the below, Console.Writeline will throw a "Cannot access a closed Stream."

class Program
{
static MemoryStream GetMemoryStream()
{
using (MemoryStream mem = new MemoryStream())
{
// BAD CODE - BUG!
return mem;

// The above will return an object which is about to be Disposed!
}
}
static void Main(string[] args)
{
MemoryStream mem = GetMemoryStream();

Console.WriteLine(mem.Length);
}
}

Something like the below would work, this maintains the using incase a Exception is thrown above the return. You'll need to manually Dispose newMem at some point in the future if the return is successful.

        var newMem = new MemoryStream();
mem.CopyTo(newMem);
return File(newMem, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");

Cannot access a closed Stream of a memoryStream, how to reopen?

How can I reopen a closed memory stream?

You can't reopen the stream. If you need to "reset" the stream, just assign it a new instance:

memoryStream = new MemoryStream();

Cannot access a closed Stream? How to prevent it?

You're creating the MemoryStream in a using block. When the block goes out of scope the Dispose method is being called. Just remove the using so that it isn't closed:

var output = new MemoryStream())

var qualityParamId = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality);
var codec = ImageCodecInfo.GetImageDecoders()
.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);

resized.Save(output, codec, encoderParameters);

return output;

Also, if you're planning to have the caller read the stream then you'll probably want to reset the Position property so that anyone reading from it starts from the beginning:

output.Position = 0;
return output;

Cannot access a closed Stream when returning FileStreamResult from C# .NetCore API

Using statements close and unload the variable from memory set in the using statement which is why you are getting an error trying to access a closed memory stream. You don't need to use a using statement if you are just going to return the result at the end.

Using statements are useful for taking care of removing data from memory for you but you could always dispose of the data yourself using .dispose()



Related Topics



Leave a reply



Submit