如何在Response.end之后执行代码

时间:2013-05-24 09:30:07

标签: c# asp.net

我的代码就像这样

HttpContext.Current.Response.Clear();
     HttpContext.Current.Response.ContentType = "application/pdf";
     HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + "name" + ".pdf");
     HttpContext.Current.Response.TransmitFile("~/media/pdf/name.pdf");
     HttpContext.Current.Response.End();
     if (FileExists("/media/pdf/name.pdf"))
     {
         System.IO.File.Delete("D:/Projects/09-05-2013/httpdocs/media/pdf/name.pdf");
     }

这里我想在浏览器中下载name.pdf,下载后我要删除该文件。但代码执行停止在

HttpContext.Current.Response.End();

执行该行后没有代码。所以我的删除功能无效。是否有解决此问题的方法?

4 个答案:

答案 0 :(得分:4)

HttpResponse.End(根据documentation)提出ThreadAbortException,因为您没有尝试处理此问题,您的方法会退出。

我不确定你为什么必须使用End(),但你可以将“清理”代码放在finally语句中。

答案 1 :(得分:3)

// Add headers for a csv file or whatever
Response.ContentType = "text/csv"
Response.AddHeader("Content-Disposition", "attachment;filename=report.csv")
Response.AddHeader("Pragma", "no-cache")
Response.AddHeader("Cache-Control", "no-cache")

// Write the data as binary from a unicode string
Dim buffer As Byte()
buffer = System.Text.Encoding.Unicode.GetBytes(csv)
Response.BinaryWrite(buffer)

// Sends the response buffer
Response.Flush()

// Prevents any other content from being sent to the browser
Response.SuppressContent = True

// Directs the thread to finish, bypassing additional processing
HttpContext.Current.ApplicationInstance.CompleteRequest()

答案 2 :(得分:1)

可能会触发一些异步方法(触发并忘记样式)来删除文件或在服务器上安装一个清理服务,以便在一定的时间和规则后删除所有文件。

就像提到Reponse.End相当苛刻和最终...更多细节在这里: Is Response.End() considered harmful?

只是我的想法... =)

答案 3 :(得分:1)

我有同样的问题。 试试这个:复制到MemoryStream - >删除文件 - >下载。

string absolutePath = "~/your path";
try {
    //copy to MemoryStream
    MemoryStream ms = new MemoryStream();
    using (FileStream fs = File.OpenRead(Server.MapPath(absolutePath))) 
    { 
        fs.CopyTo(ms); 
    }

    //Delete file
    if(File.Exists(Server.MapPath(absolutePath)))
       File.Delete(Server.MapPath(absolutePath))

    //Download file
    Response.Clear()
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + absolutePath + "\"");
    Response.BinaryWrite(ms.ToArray())
}
catch {}

Response.End();
相关问题