Search code examples
c#asp.net-core.net-5memorystreamasp.net5

How to return a MemoryStream as an Excel file from IActionResult in Asp.Net Core


I'm working on an Asp.Net Core project targeted .Net 5.

I have this ActionResult :

     public async Task<ActionResult> ExportMarksForm(int testId)
            {
                var stream = new MemoryStream();
                // Some logic to Save the workbook as stream

                return File(stream, "application/ms-excel", "xxx.xlsx");
            }

The problem: Everything works fine but when I downloaded the file I got an excel message that told me that the file is damaged, that is means an error happened or the file writing operation not complete.

I tried break points and I saw that the stream variable has bytes.

So, please how can I fix this issue? or if there is any other solution to return a stream as an Excel file please share it with me. Thanks in advance.


Solution

  • I fixed the Issue by using FileStreamResult:

    return new FileStreamResult( stream , "application/ms-excel" )
                       {
                           FileDownloadName = "xxx.xlsx"
                       };