user3492682
user3492682

Reputation: 17

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

Upvotes: 0

Views: 13199

Answers (3)

Delta
Delta

Reputation: 161

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

Upvotes: 5

Mohamed Farrag
Mohamed Farrag

Reputation: 1692

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

Upvotes: 0

Related Questions