2

My code is like this

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");
     }

Here I want to download name.pdf in the browser, and after the download I want o delete that file.But the code execution stops at

HttpContext.Current.Response.End();

no code after that line is executed.so my delete function is not working.Is there any work around for this issue?

None
  • 5,582
  • 21
  • 85
  • 170

4 Answers4

5
// 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()
Mayur Borad
  • 1,295
  • 9
  • 23
4

HttpResponse.End (as per documentation) raises a ThreadAbortException and as you do no attempt to handle this your method exits.

I'm not sure exactly why you must use End(), but you could put the "cleanup" code in a finally statement.

Marcus
  • 5,987
  • 3
  • 27
  • 40
1

Maybe fire some async method (fire and forget style) to delete the file or have a clean-up service on the server to delete all your files after certain time and rule.

Like mentioned about Reponse.End is pretty harsh and final... more details here: Is Response.End() considered harmful?

just my thoughts on that... =)

Community
  • 1
  • 1
silverfighter
  • 6,762
  • 10
  • 46
  • 73
1

I had the same issue. try this: copy to MemoryStream -> delete file -> download.

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();