Response.TransmitFile and delete it after transmission

Radhi picture Radhi · Apr 22, 2010 · Viewed 20.1k times · Source

I have to implement GEDCOM export in my site.

My .net code created one file at server when export to gedcom clicked.

Then I need to download it to client from server, as well as user should be asked where to save that file, meaning savedialog is required.

After it's downloaded, I want to delete that file from server.

I got one code to transmit file from server to client:

Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.TransmitFile(Server.MapPath("~/" + FileName));
Response.End();

from this LINK

but I am not able to delete the file after this code as Response.End ends response so whatever code written after that line is not execute.

If I do code to delete file before Response.End();, then file does not transmitted and I get an error.

Answer

Josh picture Josh · Apr 22, 2010

Anything you put after Response.End won't get executed because it throws a ThreadAbortException to stop execution of the page at that point.

Try this instead:

string responseFile = Server.MapPath("~/" + FileName);

try{
    Response.ContentType = "text/xml";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.TransmitFile(responseFile);
    Response.Flush();
}
finally {
    File.Delete(responseFile);
}