简体   繁体   中英

Getting File downloading issue in asp.net?

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

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.

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