Reputation:
I'm attempting to provide a link to download a zip file on an asp.net webpage but just can't get it working.
Can anyone spot what I'm doing wrong?
I have the following link
<a href="#" runat="server" ID="lnkDownload"
Text="Download Zip" onServerClick="DownloadFile">Download TestFile</a>
and codebehind,
protected void DownloadFile(object sender, EventArgs eventArgs)
{
string DownloadPath = "/Members/Download/TestFile.zip";
//string DownloadPath = "~/Members/Download/TestFile.zip";
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition",
"attachment; filename=\"" + "TestFile.zip" + "\"");
Response.Clear();
Response.WriteFile(DownloadPath);
Response.End();
}
The code runs when the link is clicked but nothing downloads and I then get an error on Response.End();
which is
A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll
Upvotes: 1
Views: 323
Reputation: 3662
Try this code:
Response.AddHeader("Content-Disposition", "attachment; filename=" + DownloadPath);
Response.ContentType = "application/octet-stream";
Response.TransmitFile(DownloadPath);
Response.Flush();
--- Updated code
var fileInfo = new System.IO.FileInfo(DownloadPath);
if (fileInfo.Exists)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.BufferOutput = true;
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.TransmitFile(fileInfo.FullName);
Response.Flush();
}
else
{
throw new Exception("File not found");
}
Upvotes: 1