tags:

views:

242

answers:

3

I want to delete a file immediately after download, how do I do it? I've tried to subclass FilePathResult and override the WriteFile method where I delete file after

HttpResponseBase.TransmitFile

is called, but this hangs the application.

Can I safely delete a file after user downloads it?

+2  A: 

You could create a custom actionfilter for the action with an OnActionExecuted Method that would then remove the file after the action was completed, something like

public class DeleteFileAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutingContext filterContext) 
    { 
        // Delete file 
    } 
} 

then your action has

[DeleteFileAttribute]
public FileContentResult GetFile(int id)
{
   ...
}
Israfel
The download hangs and never finishes, ideas?
Valentin Vasiliev
Of course, I wasnt thinking, you're deleting the file before the download is complete. Could you not delete the previously generated file before each request for a new result, thats what I've done in a similar sounding situation.
Israfel
does this gives solution
Krunal
It adds unnecessary complexity, I should store downloaded files in DB then since there is no way to keep the previos file known to subsequent.
Valentin Vasiliev
A: 

My used pattern.

1)Create file.

2)Delete old created file, FileInfo.CreationTime < DateTime.Now.AddHour(-1)

3)User downloaded.

How about this idea?

takepara
Please see my answer, it actually works now
Valentin Vasiliev
A: 

SOLUTION:

One should either subclass the FileResult or create a custom action filter, but the tricky part is to flush the response before trying to delete the file.

Valentin Vasiliev