Note that there are some explanatory texts on larger screens.

plurals
  1. POForce download ASP.Net
    text
    copied!<p>In ASP.Net (with C#) I'm trying to create a .DAT file with plain text in it and send it to the browser and force download. I've tried several things but I can't get it working. In my aspx-file there is an <code>ImageButton</code></p> <pre><code>&lt;asp:ImageButton ID="btnSave" runat="server" CausesValidation="False" ImageUrl="~/Images/Stages/Database/Save.png" OnClick="btnSave_OnClick" Width="26px" /&gt; </code></pre> <p>In the OnClick-method I'm trying to create the file and send it to the browser.</p> <pre><code>protected void btnSave_OnClick(object sender, EventArgs e) { string file = "test.dat"; string fileName = "~\\Stages\\Broekx\\Databanken\\" + file; FileStream fs = new FileStream(MapPath(fileName), FileMode.Open); long cntBytes = new FileInfo(MapPath(fileName)).Length; byte[] byteArray = new byte[Convert.ToInt32(cntBytes)]; fs.Read(byteArray, 0, Convert.ToInt32(cntBytes)); fs.Close(); ImageButton btnSave = (ImageButton)FormViewStagesDummy.FindControl("btnSave"); btnSave.Visible = false; File.Delete(Server.MapPath(fileName)); if (byteArray != null) { this.Response.Clear(); this.Response.ContentType = "text/plain"; this.Response.AddHeader("content-disposition", "attachment;filename=" + file); this.Response.BinaryWrite(byteArray); this.Response.End(); this.Response.Flush(); this.Response.Close(); } } </code></pre> <p>The file test.dat exists in the correct folder and has to be deleted after it has been read into bytes. I've tried this without deleting the file and that wont work either.</p> <p>After clicking btnSave the button has to be hidden, so that's why I set the parameter Visible to false.</p> <p>I've also tried it with content-type "application/octet-stream" or with a PDF file and content-type "application/pdf" but nothing works. The page loads normally and no file is being downloaded.</p>
 

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