Reputation: 2434
I am trying to get a file from my Server.Mappath("/Test.txt"); file. I am getting an error
code
proteced void lnkDownload_Click(object sender,EventArgs e)
{
string strFileName = lnkDownload.Text;
string path = Server.MapPath("~/Attachments//" + strFileName);
try
{
if (File.Exists(path))
{
byte[] bts = System.IO.File.ReadAllBytes(path);
MemoryStream ms = new MemoryStream(bts);
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + strFileName + "\"");
Response.TransmitFile(path);
Response.End();
}
}
catch(Exception ex)
{
throw ex;
}
}
Error : When code execution reaches to Response.End() there it is giving some unknown error
exception details showing like above attached image. But final exception comming like
System.Threading.ThreadAbortException: Thread was being aborted.
at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort(Object stateInfo) at System.Web.HttpResponse.End()
Upvotes: 0
Views: 2588
Reputation: 2434
Got the solution. it is working on editing the code.
protected void lnkDownload_Click(object sender, EventArgs e)
{
string strFileName = "Test.txt";// lnkDownload.Text;
string path = Server.MapPath("~/Attachments//" + strFileName);
//try
//{
if (File.Exists(path))
{
byte[] bts = System.IO.File.ReadAllBytes(path);
MemoryStream ms = new MemoryStream(bts);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + strFileName + "\"");
Response.TransmitFile(path);
Response.End();
}
//}
//catch (Exception ex)
//{
// throw ex;
//}
}
Firstly, I addded the following code at the begining of Page_Load event.
Response.Clear();
Secondly,removed 'Response.End();' into try catch block, it was causing the problem i mentioned earlier.
We can remove it and use it directly.
Response.End(), aborts the current thread. if we call inside a try block,we need to catch the thread abort. if we use a try block, then need to catch the abort and re-throw it.
Upvotes: 1