繁体   English   中英

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

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

我正在尝试从Server.Mappath(“ / Test.txt”);获取文件。 文件。 我收到一个错误

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

}

错误:代码执行到达Response.End()时,出现了一些未知错误

在此处输入图片说明

异常详细信息如上图所示。 但是最终的异常像

System.Threading.ThreadAbortException:线程正在中止。

在System.Threading.Thread.AbortInternal()

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

得到了解决方案。 它正在编辑代码。

 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;

    //}    

}

首先,我在Page_Load事件的开始处添加了以下代码。

Response.Clear();

其次,删除了“ Response.End();” 进入try catch块,这导致了我前面提到的问题。

我们可以将其删除并直接使用。

Response.End(),中止当前线程。 如果在try块内调用,则需要捕获线程中止。 如果我们使用try块,则需要捕获异常并重新抛出它。

暂无
暂无

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

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