C# .Net-Core 3.1
In my C# api I am returning a pdf file in a FileStreamResult, works great.
Generally I wrap streams in using, however this code fails with
Cannot access a closed Stream
.
using (MemoryStream stream = new MemoryStream(byteArray))
{
fileStreamResult = new FileStreamResult(stream, "application/pdf");
}
return (ActionResult)fileStreamResult;
So I need to do this:
var stream = new MemoryStream(byteArray);
fileStreamResult = new FileStreamResult(stream, "application/pdf");
return (ActionResult)fileStreamResult;
I'm assuming the stream needs to remain open, should I be concerned about memory leaks or does IIS close the stream? Are there better alternatives?
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()