简体   繁体   中英

Do I need to close this memory stream?

I have this code which works:

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

However, it seems to me that I somehow need to be closing or disposing of the memoryStream. Is that correct? Or is it getting automatically closed?

Since the memory stream is encapsulated in the return value, you should not dispose it. If you do, it will be disposed before the FileStreamResult can access it.

The stream is already disposed inside the FileStreamResultExecutor.ExecuteAsync method, as you can see in the source .

The same is true for ASP.NET MVC, where is it FileStreamResult.WriteFile that does the disposal ( source ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM