1

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?

4

2 回答 2

2

Using 语句关闭并从 using 语句中设置的内存中卸载变量,这就是尝试访问关闭的内存流时出错的原因。如果您只是要在最后返回结果,则不需要使用 using 语句。

using 语句对于为您从内存中删除数据很有用,但您始终可以使用 .dispose() 自己处理数据

于 2020-04-22T13:09:25.590 回答
0

为什么要return (ActionResult)fileStreamResult;在外面使用块?

于 2020-04-22T13:03:44.950 回答