如何使用ASP.NET下载文件

时间:2014-04-16 10:32:36

标签: c# asp.net

在下面的代码中,我想从本地下载文件,当我点击链接按钮时,它应该从特定路径下载文件。在我的情况下,它抛出

  

' C:/Search/SVGS/Documents/img.txt'是物理路径,但预计会有虚拟路径。

protected void lnkbtndoc_Click(object sender, EventArgs e)
{
    LinkButton lnkbtndoc = new LinkButton();
    var SearchDoc = Session["Filepath"];
    string file = SearchDoc.ToString();
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + file + "\"");
    Response.TransmitFile(Server.MapPath(file));
    Response.End();
}

3 个答案:

答案 0 :(得分:3)

使用以下代码在链接按钮上下载文件

<asp:LinkButton ID="btnDownload" runat="server" Text="Download"
            OnClick="btnDownload_OnClick" />
protected void btnDownload_OnClick(object sender, EventArgs e)
    {
        string filename = "~/Downloads/msizap.exe";
        if (filename != "")
        {
            string path = Server.MapPath(filename);
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("This file does not exist.");
            }
        }
    }

答案 1 :(得分:0)

答案 2 :(得分:0)

在您的代码中只需更改此行:

Response.TransmitFile(Server.MapPath(file));

Response.TransmitFile(file);

这是因为您发送的物理路径不是Server.MapPath期望的虚拟路径。另请阅读此article,它将帮助您了解如何处理Server.MapPath方法