简体   繁体   中英

How to download a file using 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

'C:/Search/SVGS/Documents/img.txt' is a physical path, but a virtual path was expected.

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

In your code just change this line :

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

to

Response.TransmitFile(file);

This because of you are sending the physical path not the virtual path as Server.MapPath expects. Also read this article it will help you to understand how to deal with Server.MapPath method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM