ASP.NET download file from server

553 views Asked by At

I'd like to download a file from server to the client. Neither of the solutions I found across internet works, they all write the file to the server, but never pops the download window on the client's browser. I don't know whether it is a ASP.NET issue or IIS.

This is my code:

Workbook wb = getExcel();
string pathDownload = HttpContext.Current.Server.MapPath("~/Content/DOCUMENTS/temp/Excel.xls");

BIFF8Writer.WriteWorkbookToFile(wb, pathDownload);
byte[] fileContent = System.IO.File.ReadAllBytes(pathDownload);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=Excel.xls");
HttpContext.Current.Response.BinaryWrite(fileContent);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
1

There are 1 answers

3
Peter Hahndorf On

Since WriteWorkbookToFile already writes the file in question to the file system, it is preferable to use it straight from there rather than load it into memory and then do a BinaryWrite.

remove the line:

byte[] fileContent = System.IO.File.ReadAllBytes(pathDownload);

and then replace the line:

HttpContext.Current.Response.BinaryWrite(fileContent);

with:

HttpContext.Current.Response.TransmitFile(pathDownload);