views:

652

answers:

2

Hi,

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 to where to save that file means savedialog is required. after its 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 whtever code written after that line is not execute. if i do code to delete file before Response.End(); then file does not transmitted and got error.

so, please can anybody provide me any solution for this. -Thanks in advance

A: 

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();
Guffa
Hi, does Response.TransmitFile and Response.BinaryWrite have any difference in performace?
Radhi
@Radhi: Not really. BinaryWrite is faster of course as you already have the data in memory, but together with loading the data it does the same thing as TransmitFile.
Guffa
+2  A: 

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);
}
Josh Einstein
What Response.Flush does and what Response.End does?? can please let me know difference?
Radhi
Response.Flush forces out any buffered output (if there is any) but does not throw the ThreadAbortException - the response is still in progress. Response.End flushes but then throws a ThreadAbortException which cannot be stopped. Putting the delete code in the Finally block ensures that it will run no matter what the outcome.
Josh Einstein