Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.TransmitFile and delete it after transmission

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.

like image 612
Radhi Avatar asked Apr 22 '10 04:04

Radhi


2 Answers

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);
}
like image 198
Josh Avatar answered Nov 12 '22 09:11

Josh


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();
like image 44
Guffa Avatar answered Nov 12 '22 07:11

Guffa