我需要关闭此内存流吗?

时间:2018-09-14 09:35:05

标签: c# asp.net-core asp.net-core-2.0

我有这段有效的代码:

public async Task<IActionResult> OnGet()
{
    var workbook = GenerateClosedXMLWorkbook();
    MemoryStream memoryStream = new MemoryStream();
    workbook.SaveAs(memoryStream);
    memoryStream.Position = 0;
    return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "hello.xlsx");
    }


private XLWorkbook GenerateClosedXMLWorkbook()
{
    var workbook = new XLWorkbook();
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = "Hello World!";
    worksheet.Cell("A2").FormulaA1 = "=MID(A1, 7, 5)";
    return workbook;
}

但是,在我看来,我似乎需要以某种方式关闭或处置memoryStream。那是对的吗?还是会自动关闭?

1 个答案:

答案 0 :(得分:4)

由于内存流封装在返回值中,因此您不应处置它。如果这样做,它将在FileStreamResult访问之前被丢弃。

该流已经放置在FileStreamResultExecutor.ExecuteAsync方法内部,如您在the source中所见。

对于ASP.NET MVC,情况也是如此,FileStreamResult.WriteFile在哪里处理(source)。