title: Downloading .xls file with Response.WriteFile downloads file with webpage content
body: <p>I have a simple ASP.NET webpage using VB with a file upload control. The user will upload a .xls and a new .xls file is created in the project directory with a new format and some calculations. This file saves, opens, and displays without an issue. </p>
  
  <p>Within this button click event, I want the newly-created file to download to the user's browser/Downloads folder. When using Response.WriteFile with a Response.End, the .xls file downloads properly...BUT there's a thread abort exception that is caught and nothing after the Response.WriteFile line is processed even if I put it in the catch statement (i.e. I have a label that I want to tell the user to then display that the file has been successfully downloaded).</p>
  
  <p>Here's the initial code that mostly works:</p>
  
  <pre><code>Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
          If fuReport.HasFile Then
  
  'All report processing occurs &amp; report is created without issue
  
      Try
          Response.Clear()
          Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", strReportName))
          Response.ContentType = "application/vnd.ms-excel"
          'Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          Response.WriteFile(strReportName)
          Response.End()
          lblResult.Text = "Report was successfully downloaded."
       Catch
          lblResult.Text = "Testing1."
       Finally
          lblResult.Text = "Testing2."
          fuReport = New FileUpload()
       End Try
      End If
      End Sub
  </code></pre>
  
  <p>I've seen some different recommendations for the ContentType of .xls files. Both of the content types above will download the file but nothing in the Catch or Finally statement is processed. lblResult still reads, "Please wait while your report is processing..."</p>
  
  <p>I found online that the issue lies with Response.End(). Per <a href="https://support.microsoft.com/en-us/kb/312629/en-us" rel="nofollow">https://support.microsoft.com/en-us/kb/312629/en-us</a>, I replaced this with </p>
  
  <pre><code>HttpContext.Current.ApplicationInstance.CompleteRequest()
  </code></pre>
  
  <p>This caused a new issue. My .xls file would download, but it seemed to display gibberish, followed by some of the aspx page content. Here, the label is correctly listed even though it has not changed on the webpage. I don't have enough reputation to include a screenshot, but this is some of what the Excel file displays:</p>
  
  <pre><code>ˆdQ_9€`Èb/ecÈ¢l†=gÊC\Œ¬ÀxbY”Â…‘#ˆ,ör6ˆ,Ê…8ëY8ÖæBô?³2º‹CÓž€|^î¯{{&lt;xJñ¯ªç2,FÑ+sbŸ£å›q³žcm"9ŸÛÆ…îâpoŸûñä_õ¥1­K×Ê1Ü–‘äŒä‚$‹’,ÊÞÿ?ëY9ÖÎÉºa 9†7(Æ‘E‰c&lt;µŠ$wïå¼Q9çƒìù93vì£Þ¾ŠõXè.î·ÛúÏöX;`&gt;¸w!‚™•óÂ‘#Ž,8²(ãÞqÖ3q¬M¥dÝ ‚Â7VE¾‰`|mä^@Y”°çÞÌØZXß²‹O•½në›×å­=än½‘°i”EàqÅ^Ê6‹²(×›õìks   žú¦¸Ð½µW§îo[‚‡ÚGÈýz3·!dÑ„@ dq€E9õ×3lfl%Ø™^Vv
  @ÈB{)[²èïmÖ³l¬…8óI–½-?o{ÖÎ¤,÷Ä²hC ²ØKÙ²hmïÕÎžâ}û‡.vÝÌznµ³ð±Lâc¹7†E  ÜOpÁÅ^ÎÆEyüæ=£ÆÚÄÏnïýúº·7åå‡v³Í[;Î¿Šþ•PˆÃp%*0B!ö
  ÑÓè¼gÓX›8N—ï\èõXèÞÞ4·íTÏöõeùí$ñõ­~À“Böº/kûÏµýõ\Þ8½&gt;SF+/åê1³{þÌœý†éêÔßŠ*t-Áwí&gt;ÕnW¿¯öÎ€žE” 9åÕÈFY”ùöâ¼gÏX›*Ñ^¸ñÓ*‘uo›ËK;”Áð/. 
  ½g/D‰ ?KQFþÝF3©ö|š9›1JÖi”¬÷m6‘lB/oD‘s0²èŒ=·fÎvBŒ‘u#ëŒ,JãK#YPdÑ1{ŽÍœ{+&lt;˜WY÷v_ï®ÚÇ½ªêë{ñæÑ½Ð–9ÅëÚ–9,À’–,X²(×z›÷ÌkÓÒö;+»&gt;²ì6£®ËÛwÁýë½á0‚,JaRå!‹½œm¥Ê¢×vôúÁìÉï¼éŸ÷&lt;kÁé*øLƒÐýËNÖ|SloŸmë¿ìÍ©ƒ·ú·Å*÷ï½Ðl(Y”PÆ+$YdQv1öü›9‹qT¬kQþk[W‡;+õ…›âš"z÷FÅ@r×   ¤X³rA“Å^ÞV—,:â2¹è:Ö¦Úœ-fþô*t”×Õî®ª·í»©ÁÛþ"„¢D3,K€A
  ±RˆòMYôÌkç1dÝ †"`È¢Ä0¾JŠ_, r÷DeBìù9vìÌTS±ÐýQnm‹x;©îªƒ³P:‹^ùJ”ÆeÈ?Wdq@EÙïN-zfŽµ±Cˆ¬‘xV AdQ‚uÈEY”O±çã,Øf°ÃyE±ÝU}gÞøÛò]mŸ;ök‘{öWª¢Û„1®EÑë“Éé“ñ©ûRÃsõ£ŠÜcælÚópì1ÄY7!Gð}U‘nB•ÈÝŠJdqÀE™{Î‚½…˜!ë†0äC%†|Ÿ!~´àÈ)Y”É±gà,Ø`˜¬‚… 
  Ëþ¨¶—;oì‰q°óFtì    
  ‡]¹Û„1žM9€ Èb/åJ9cóÔ¢çÞX×4‹¹wY²«!ëþ¨+û4Š8¿z*"xƒaü¸ÛÄ¦RŽ ²ØËÙ²({ø¢çÜX›0Ž‚³n…ì;V£.oÇ§kŠ Þ HN8Œ‘Ž,öR6Ž,Ê›J—=·ÆÚqí$:£xÛÞ$Ú‹R‡ÏîÂTðŸM    Q"ÈWD…1
  ±Qˆr?8µìY6ÖÎÉº 9€7 ÅXd›@Æsªˆ  ~Î•s6Äže³dG!®FÖ  
  €Èˆ,JÃùTü\Á{÷R6†,ÊfØsl–ì'Ì#Ï;Y…ÎÚ5ñäo'›}]í.Gßú“+çà›¨"8¹W“ÅNñDcÙso¬ÍSkD”ußG”cyÃc³,‹Q˜e9‚@Êb/g«Pƒ´çæ,Ùj°"õß¾º?êÝ‡v+ÇoÍv,{¸coLŒ#‹†pä‚#‹½œ#‹ŽáØst–l5Ìã`²eÝÍÎÎ¿Y—ûwöBŽ?ÃrßÐÙ&amp;ŽbùÊ]–,X²(oëñ²gèX›gØàb¡û£i®Ì/ªwÍ¾ôwrˆGN7q„y•#†,²(w+Ç²çëX›).¼…‡­|X÷ÇÞöÅÙ!Föjc|ûFDðFÄfUî6QŒ—¯@@d±—²Mª,:fRí;K6ìˆ¿€#ë†päÞ G%ŽPA€d±—³dÑ W=sÇÚ\sÏfY…î¿ÛÅ÷íƒÇÆM\è½¿žBuš0†å(zeŠBìS¢c(öœ›¶ïØ·Ë…î¿Û×S‹ªjÿÏ]â}@‘“@‘Š,(²(Ïc]õ\kc†Y§²Þ    
  +C%€¼FQENÁË{£òÎ¤ØóuVì5ÄeÈ:M‘õÞhE%Šñ5QD¹{/g#È"$øäî¦ªEy(ýùãMc;ÓêË×û“÷Íîð«_~°ëàáóÇê—vÍY³ûÓü3Û}þÃûomWi{˜[½»;ÙVïöŸþÔnxXrþçš¿ü`“Ä;ûä[sûÐ¼©ì½õ}ûØü¾ilGÜ—ÿa1¿ü»çÿð¤ÜÖ×»?l{Î×^ì¿jû}ò©ÙxÈù×ÿÿÿPK-!®ÄñQ"[Content_Types].xmlPK-!ùJ­¬öW 
  sxl/styles.xmlPK-!é¦%¸‚Sü  xl/theme/theme1.xmlPK-!òñ%&gt;e¯docProps/core.xmlPK-! pUŠ¡5$docProps/app.xmlPK-!Š¥aú`qûxl/workbook.xmlPK-!'¡Œ=Å5ßˆxl/worksheets/sheet1.xmlPK
  
  &lt;!DOCTYPE html&gt; 
  
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; 
  &lt;head id="Head1"&gt;&lt;title&gt;    
  
  &lt;/title&gt;    
      &lt;script type="text/javascript"&gt; 
          function changeLabel(){ 
              document.getElementById("lblResult").innerHTML = "Please wait while your report is processed...";   
          }   
      &lt;/script&gt;   
  &lt;/head&gt; 
  &lt;body&gt;  
  
      &lt;form method="post" action="Uploader.aspx" id="form1" enctype="multipart/form-data"&gt;    
  &lt;div class="aspNetHidden"&gt;  
  &lt;input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="+yve+0TnTzr8dZbqET3gRkZx/Pw9iGFmDqDyyfeTPMoXlPTPVgX3FrRUhTd3lBZE0DkzyUKzhXOi6MqTdxe1jnYL+mdzQiyoaM5w5cv9vij3X1xtsW8P1zACrDj6IqUK87n3GcwFtdHCCblAdgFI8nPQZsJnRv9w8lNIurcrbfad534ICOt8S/++vRi9+s91DFi3woIbFMyxw3rvbUPQwg==" /&gt;    
  &lt;/div&gt;  
  
  &lt;div class="aspNetHidden"&gt;  
  
      &lt;input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="C153B6F1" /&gt;
      &lt;input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="c3fKPUwILazJv1aW60quCxYtkspAHgetjdwMb7ugaEBN7qnUTTL7SrAVizVMaqXPAPqmyhDV0rtT1upkWYH9eOzqHjjmjvr9ZHty08BHB9OD/fCIuF8ExZbOqpiXOdGA" /&gt;
  
  
   &lt;/div&gt; 
  
  
    &lt;div&gt; 
          &lt;input type="file" name="fuReport" id="fuReport" style="width:306px;" /&gt;    
          &lt;br /&gt;  
          &lt;span id="lblResult"&gt;Report was successfully downloaded.&lt;/span&gt; 
          &lt;br /&gt;          
          &lt;input type="submit" name="btnUpload" value="Upload" onclick="changeLabel();" id="btnUpload" /&gt; 
      &lt;/div&gt;      
      &lt;/form&gt; 
  &lt;/body&gt; 
  &lt;/html&gt; 
  </code></pre>
  
  <p>I then tried replace all of the Response code with HTTPContext as shown here:</p>
  
  <pre><code>HttpContext.Current.Response.ClearContent()
  HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", strReportName))
  HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
  HttpContext.Current.Response.Write(strReportName)
  HttpContext.Current.ApplicationInstance.CompleteRequest()
  </code></pre>
  
  <p>This also downloads a .xls file but with a graphical representation of the webpage. Again, I cannot post a picture, but the Excel file opens to show the button with text, Upload &amp; says:</p>
  
  <p>Report was successfully downloaded.</p>
  
  <p>I have researched this for HOURS with no solution. I have tried pulling this particular code out of the try/catch/finally as someone else had success with but this did not help either.</p>
  
  <p>Does anybody know how I can properly have the browser download the .xls file with the actual contents of my NewReport instead of it containing information from the aspx page??</p>