I have an asp.net application where the user can download a file by clicking a link. It could be a file of any type. Getting it work took more effort than expected. Let me use my blog as a public notepad and share the result.
protected void LinkButtonDownLoad_Click(object sender, EventArgs e)
{
string bestandsnaam = (sender as LinkButton).CommandArgument;
string fullFileName = Server.MapPath("DownLoads") + "\\" + bestandsnaam;
if (System.IO.File.Exists(fullFileName))
{
bestandsnaam = Server.UrlPathEncode(bestandsnaam);
Response.Clear();
Response.ContentType = "application/binary";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", bestandsnaam));
Response.TransmitFile(fullFileName);
Response.Flush();
Response.End();
}
}
The name of the file (bestandsnaam in Dutch:) is read from the linkbutton's CommandArgument as that's a bindable property. UrlPathEncode is necessary for filenames containing blanks. The ContentType is set to application/binary to make sure any format will get across safely.
Thanks to me neighbor who used to blog and is still an invaluable resource. The code is no big deal but we had to assemble it ourselves being unable to find a full working example.