本文介绍了如何使用ASP.NET下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,当我单击链接按钮时,我想从本地下载文件,它应该从特定路径下载文件.就我而言,它会抛出

In the below code i want to download a file from local when i click link button it should download a file from specific path. In my case it throws

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

推荐答案

使用以下代码在链接按钮单击时下载文件

Use the below code to download the file on link button click

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

这篇关于如何使用ASP.NET下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 14:12