Question

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.

Was it helpful?

Solution

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

OTHER TIPS

If the file is reasonably small, you can load it into a byte array so that you can delete the file while still being able to send the data:

Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
string path = Server.MapPath("~/" + FileName);
byte[] data = File.ReadAllBytes(path);
File.Delete(path);
Response.BinaryWrite(data);
Response.End();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top