In ASP.Net (with C #), I am trying to create a .DAT file with clear text in it and send it to the browser and force download. I tried a few things, but I can't get it to work. In my aspx file there isImageButton
<asp:ImageButton ID="btnSave" runat="server" CausesValidation="False" ImageUrl="~/Images/Stages/Database/Save.png" OnClick="btnSave_OnClick" Width="26px" />
In the OnClick method, I am trying to create a file and send it to the browser.
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();
}
}
The test.dat file exists in the correct folder and must be deleted after reading it in bytes. I tried this without deleting the file, and this does not work either.
After clicking the btnSave button, the button should be hidden, so I set the Visible parameter to false.
I also tried it with the application content type / octet stream or with the PDF file and the content type "application / pdf", but nothing works. The page loads normally and the file does not load.