2016-07-28 41 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

相關問題