2016-07-28 40 views
0

我使用此代码来下载文件,但它会引发错误。请帮我处理它。为什么我的代码抛出线程中止错误?

线程正在中止。

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); 
    } 
} 
+0

你从哪里得到错误? 'Reponse.End()'总是抛出一个'ThreadAbortException'。看看[这个](http://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce)和[this] (http://stackoverflow.com/questions/5834049/what-c​​auses-thread-was-being-aborted-exception-to-happen-at-random-and-show-th)后。 –

+0

是相同的地方,我删除它,但它仍然没有下载文件 – Cuckoo

+0

并不抛出错误,但仍然不下载文件 – Cuckoo

回答

0

该下载方法可以工作吗?

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

希望这会有所帮助。

+0

什么是urlToFileOnInternet? – Cuckoo

+0

你不试图下载文件?引用:“我正在使用此代码下载文件” – MasterXD

+0

将文件从网络服务器下载到我自己的文件夹 – Cuckoo

0

更换

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

+0

不工作仍然没有下载 – Cuckoo

+0

@Cuckoo检查我的更新。 – Lesmian

相关问题