2013-10-25 31 views
1

下載PDF當我在asp.net問題在asp.net

try 
      { 
       string strURL = Directory.GetFiles(Server.MapPath("PDFs/PrintPDF")).SingleOrDefault(); 

       WebClient req = new WebClient(); 
       HttpResponse response = HttpContext.Current.Response; 
       response.Clear(); 
       response.ClearContent(); 
       response.ClearHeaders(); 
       response.Buffer = true; 
       response.AddHeader("Content-Disposition", "attachment;filename=\"" + strURL + "\""); 
       byte[] data = req.DownloadData(strURL); 
       response.BinaryWrite(data); 
       response.End();//At this line I am getting the error 

      } 
      catch (Exception ex) 
      { 
      } 

上面的代碼正在使用下面的代碼下載一個PDF。但要catch塊,並顯示錯誤:

"[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}" 

我已經更換了到Response.End();這條線

HttpContext.Current.ApplicationInstance.CompleteRequest(); 

的PDF是越來越下載,但無法打開PDF線。當您打開PDF亞姆得到的錯誤:

"there was an error opening this document. the file is damaged and could not be repaired" 

我使用response.Flush();沒有幫助也試過:

回答

0

我不太確定該錯誤消息的意圖,但我周圍的測試誤差得到了查看消息是否包含「線程正在中止」消息。這裏有一個例子:

 if (ex.Message.StartsWith("Thread") == false) 
     { 
      Response.Redirect("~/Error.aspx?ErrorMsg = " + ex.Message); 
     } 

此外,

請檢查該鏈接的原因和錯誤的解決方案:http://support.microsoft.com/kb/312629/EN-US/

0

我不知道這是否可以幫助你,從流打開PDF文件我使用下面的代碼對我來說工作正常,並且不會觸發任何異常。我從一個數據庫得到我的pdf,而對於pdf文件,我不使用addHeader。我希望它能幫助你。

Response.ClearContent(); 
Response.ClearHeaders(); 
Response.ContentType = "application/pdf"; 
var abyt = (Byte[]) ds.Tables[0].Rows[0]["blob"]; 
Response.BinaryWrite(abyt); 
Response.Flush(); 
Response.Close();