2013-09-30 25 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

相关问题