2013-09-30 23 views
0

我正在嘗試下載位於特定文件夾中的文件。我使用此代碼,但它給了我一個錯誤Reponse.End(); - >無法因爲代碼優化或本地幀是在調用堆棧asp.net - 下載特定文件夾中的文件

if (m.Path.EndsWith(".txt")) 
      { 
       Response.ContentType = "application/txt"; 
      } 
      else if (m.Path.EndsWith(".pdf")) 
      { 
       Response.ContentType = "application/pdf"; 
      } 
      else if (m.Path.EndsWith(".docx")) 
      { 
       Response.ContentType = "application/docx"; 
      } 
      else 
      { 
       Response.ContentType = "image/jpg"; 
      } 
      string nameFile = m.Path; 

      Response.AppendHeader("Content-Disposition", "attachment;filename=" + nameFile); 

      Response.TransmitFile(Server.MapPath(ConfigurationManager.AppSettings["IMAGESPATH"]) + nameFile); 
      Response.End(); 

我也試過Response.Write的頂部,以評估表達,但它給了我同樣的錯誤。

回答

1

Response.End將拋出ThreadAbortException和它的存在只爲compatibility with old ASP,你應該使用HttpApplication.CompleteRequest

這裏是例子:

public class Handler1 : IHttpHandler 
{  
    public void ProcessRequest(HttpContext context) 
    { 
    context.Response.AppendHeader("Content-Disposition", "attachment;filename=pic.jpg"); 
    context.Response.ContentType = "image/jpg"; 
    context.Response.TransmitFile(context.Server.MapPath("/App_Data/pic.jpg")); 
    context.ApplicationInstance.CompleteRequest(); 
    } 

    public bool IsReusable 
    { 
    get 
    { 
     return false; 
    } 
    } 
} 
+0

現在已經沒有錯誤,但也什麼都不做。不會下載該文件。 – Jcbo

+0

奇怪的是,我在ashx處理程序中試過這段代碼並且正常工作,用這個例子更新了我的答案。你是從處理程序提供的嗎? –

+0

它的工作原理:) 謝謝 – Jcbo

相關問題