Search code examples
c#asp.netfile-permissions

How to fix issue when saving Excel file to users desktop?


Trying to save an excel file to users desktop from a c# asp.net web application. This worked fine on local machine when testing but not on remote server. Can someone help me fix this issue? Thanks!

Code:

string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
FileInfo fi = new FileInfo(filePath + @"\spreadsheet.xlsx");
excelPackage.SaveAs(fi);

Error: enter image description here


Solution

  • It looks like you are perhaps using EPPplus (excelPackage.SaveAs(fi);). So if you use asp.net as your tag indicates you can send the Excel File to the browser and the user will get a Save File Dialog.

    //convert the excel package to a byte array
    byte[] bin = excelPackage.GetAsByteArray();
    
    //clear the buffer stream
    Response.ClearHeaders();
    Response.Clear();
    Response.Buffer = true;
    
    //set the correct contenttype
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    
    //set the correct length of the data being send
    Response.AddHeader("content-length", bin.Length.ToString());
    
    //set the filename for the excel package
    Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
    
    //send the byte array to the browser
    Response.OutputStream.Write(bin, 0, bin.Length);
    
    //cleanup
    Response.Flush();
    HttpContext.Current.ApplicationInstance.CompleteRequest();