2013-10-25 34 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();