无法创建从服务器下载文件的链接

时间:2014-02-10 14:48:04

标签: c# asp.net

我正试图在asp.net网页上提供一个下载zip文件的链接,但却无法使其正常工作。

有人能发现我做错了吗?

我有以下链接

<a href="#" runat="server" ID="lnkDownload" 
Text="Download Zip" onServerClick="DownloadFile">Download TestFile</a>

和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();
}

当点击链接但没有下载任何内容时代码运行,然后我在Response.End();上收到错误

A first chance exception of type 'System.Threading.ThreadAbortException' occurred in mscorlib.dll

1 个答案:

答案 0 :(得分:0)

试试这段代码:

Response.AddHeader("Content-Disposition", "attachment; filename=" + DownloadPath);
Response.ContentType = "application/octet-stream";
Response.TransmitFile(DownloadPath);
Response.Flush();

---更新了代码

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");
            }