简体   繁体   English

在asp.net中出现文件下载问题?

[英]Getting File downloading issue in asp.net?

I am trying to get a file from my Server.Mappath("/Test.txt"); 我正在尝试从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 错误:代码执行到达Response.End()时,出现了一些未知错误

在此处输入图片说明

exception details showing like above attached image. 异常详细信息如上图所示。 But final exception comming like 但是最终的异常像

System.Threading.ThreadAbortException: Thread was being aborted. System.Threading.ThreadAbortException:线程正在中止。

at System.Threading.Thread.AbortInternal() 在System.Threading.Thread.AbortInternal()

at System.Threading.Thread.Abort(Object stateInfo) at System.Web.HttpResponse.End() 在System.Web.HttpResponse.End()处的System.Threading.Thread.Abort(Object stateInfo)

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. 首先,我在Page_Load事件的开始处添加了以下代码。

Response.Clear(); Response.Clear();

Secondly,removed 'Response.End();' 其次,删除了“ Response.End();” into try catch block, it was causing the problem i mentioned earlier. 进入try catch块,这导致了我前面提到的问题。

We can remove it and use it directly. 我们可以将其删除并直接使用。

Response.End(), aborts the current thread. Response.End(),中止当前线程。 if we call inside a try block,we need to catch the thread abort. 如果在try块内调用,则需要捕获线程中止。 if we use a try block, then need to catch the abort and re-throw it. 如果我们使用try块,则需要捕获异常并重新抛出它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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