Reputation: 17
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
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
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
Reputation: 566
Check Any of these .
StreamReader Server.MapPath - Physical path given, virtual path expected
http://www.codeproject.com/Questions/624307/Server-MapPath-Physical-path-given-virtual-path-ex
Upvotes: 0