0

I have a strange situation. A code I wrote uses Excel Interop to create an XLS file and saves it to the server. This file is then transmitted using System.Web.HttpResponse, and deleted afterwards. My problem is, when I download this file from an outward facing demo site while using HTTPS instead of HTTP, the file will become corrupted during this transfer (it's fine on the server) because it's missing last 8 bytes of data. If I change the protocol to HTTP, the file transfers just fine. What am I missing? Here is the last parts of the method that performs this request.

        #region Save & Quit
        Guid guid = Guid.NewGuid();

        //Save and quit, use SaveCopyAs since SaveAs does not always work
        string fileName = "IRSReport_" + guid.ToString() + ".xls";
        string target = Server.MapPath("~/" + fileName);

        xlApp.DisplayAlerts = false; //Supress overwrite request
        xlWorkBook.SaveAs(target, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        //Release objects
        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        //Give the user the option to save the copy of the file anywhere they desire
        String FilePath = Server.MapPath("~/" + fileName);
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
        response.TransmitFile(FilePath);
        response.Flush();
        response.Close();

        //Delete the temporary file
        DeleteFile(fileName);
        #endregion
Lukas
  • 2,885
  • 2
  • 29
  • 31
  • I would remove ClearContent, Clear, Flush and Close. Also content type is incorrect, it's an xls file, it should be "application/vnd.ms-excel". And I would try not to delete the file too early... – Simon Mourier Jun 16 '15 at 21:46
  • Just solved it. It was indeed the ContentType. Simon, post your answer officially and I'll give you proper credit for it since you are the first one to get it right. – Lukas Jun 16 '15 at 21:52

1 Answers1

2

I would remove ClearContent, Clear, Flush and Close that should be useless.

Also the content type is incorrect, since it's an xls file, it should be "application/vnd.ms-excel".

And last, I would try not to delete the file too early to give a let the server send the file before you delete it.

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298