ASP.net MVC ActionResult corrupts excel file when returning from MemoryStream

I have the following action inside my controller

public ActionResult DownloadExcel()
        {
            //create and populate Excel file here
            C1XLBook testBook = new C1XLBook(); 
            //populate it here

            MemoryStream ms = new MemoryStream();
            testBook.Save(ms, FileFormat.Biff8);

            return File(ms, "application/ms-excel", "test-file.xls");           
        }

When I open the file, I get an Excel message saying that the file does not match the extension and the file opens damaged.

If I save the file to the hard drive and return it from there, everything will be fine:

return base.File(@"C:\LOGS\test-file.xls", "application/ms-excel", "test-excel.xls");

Initially, I thought that the Save function distorts it when saving it to a MemoryStream, so I saved and rebooted it back, and it was good for me to transfer it to the user - when it was saved on the hard drive and returned from there than from the MemoryStream

Any ideas? I don’t like to save the file to my hard drive too .... Also, should I be able to save it to a MemoryStream and return it from there?

: , MemoryStream MVC, ?

+5
1

, ( ms.Position = 0;), ? Save , .

+5

All Articles