【问题标题】:Why my code throws thread aborted error?为什么我的代码会引发线程中止错误?
【发布时间】:2016-12-02 14:24:44
【问题描述】:

我正在使用此代码下载文件,但它会引发错误。请帮我处理一下。

线程被中止。

protected void Download_Click(object sender, EventArgs e)
{
    try
    {
        string filePath = Convert.ToString(Attachment);
        string fullFilePath = ("../../SiteImages/" + "donald.jpg");
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(fullFilePath) + "\"");
        Response.ContentType = ContentType;
        Response.TransmitFile(fullFilePath);
        //MngLogs.InsertAuditsInfo("Tender downloaded via" + " " + MngLogs.PageName, MngLogs.UserMacAddress, MngLogs.UserIPAddress, UserID, "Download");
        //Response.End();
    }
    catch (Exception ex)
    {
        Utility.Msg_Error(Master, ex.Message);
    }
}

【问题讨论】:

  • 你从哪里得到错误? Reponse.End() 总是抛出 ThreadAbortException。看看thisthis 的帖子。
  • 是同一个地方,我删除了它,但它仍然没有下载文件
  • 并且不会抛出错误但仍然不会下载文件

标签: c# asp.net multithreading webforms transmitfile


【解决方案1】:

这种下载方法可行吗?

try
{
    using (var client = new WebClient())
    {
        client.DownloadFile(urlToFileOnInternet, pathToFileOnComputer);
    }
}
catch (Exception ex)
{
    Utility.Msg_Error(Master, ex.Message);
}

希望这会有所帮助。

【讨论】:

  • 什么是 urlToFileOnInternet ?
  • 您不是要下载文件吗?引用:“我正在使用此代码下载文件”
  • 从网络服务器下载文件到我自己的文件夹
  • 是的,但您需要下载链接才能实现这一点...您是在计算机上还是在您的网络服务器上运行此代码?
【解决方案2】:

替换

Response.End();

用这个:

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();

Response.End(); 总是抛出异常,因为它将中止当前线程。您可以在此处阅读有关此行为的更多信息:Is Response.End() considered harmful?How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多