Note that there are some explanatory texts on larger screens.

plurals
  1. POCalling Response.TransmitFile() from static method
    primarykey
    data
    text
    <p>I have a number of pages which need to support exporting data to an Excel spreadsheet. I can generate the Excel files just fine, but I'm trying to work out how to abstract this behavior so it's easily reusable from all of the pages where I need it. My current idea is to use a static utility method, as follows:</p> <pre><code>public static void SendExcelFile(System.Web.UI.Page callingPage, string downloadFileName, List&lt;List&lt;string&gt;&gt; data, string worksheetTitle) { string tempFileName = Path.GetTempFileName(); try { // Generate file using ExcelPackage GenerateExcelDoc(tempFileName, data, worksheetTitle); callingPage.Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadFileName); callingPage.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; callingPage.Response.AddHeader("Content-Length", new FileInfo(tempFileName).Length.ToString()); callingPage.Response.TransmitFile(tempFileName); } finally { //When this is removed, the method works as expected. if (File.Exists(tempFileName)) File.Delete(tempFileName); } } </code></pre> <p>The click handler where I'm calling <code>SendExcelFile</code> looks like this:</p> <pre><code>protected void lnkExport_Click(object sender, EventArgs e) { List&lt;List&lt;string&gt;&gt; dataList = GatherDataForSpreadsheet(); Utility.SendExcelFile(this, "fileNameForDownload.xlsx", dataList, "MyReports"); } </code></pre> <p>This code works just fine as an instance method of the calling page. As a static method, though, it doesn't work at all. When I click the button that invokes this, the browser shows the loading animations indefinitely, but never prompts for a file download.</p> <p>I'm very new to ASP.NET (and web programming in general), so I'm sure I'm missing something here. Could someone please explain the behavior I'm seeing, and suggest a reasonable alternative to this approach?</p> <p>EDIT: If I remove the call to File.Delete() at the end, the method works as expected. Does Response.TransmitFile() do the transfer asynchronously?</p> <p>EDIT 2: I just needed to call Response.Flush() before I deleted the file. See my answer below. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload