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
My used pattern.
1)Create file.
2)Delete old created file, FileInfo.CreationTime < DateTime.Now.AddHour(-1)
3)User downloaded.
How about this idea?
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(ActionExecutedContext filterContext)
{
// Delete file
}
}
then your action has
[DeleteFileAttribute]
public FileContentResult GetFile(int id)
{
...
}
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.
Read in the bytes of the file, delete it, call the base controller's File action.
public class MyBaseController : Controller
{
protected FileContentResult TemporaryFile(string fileName, string contentType, string fileDownloadName)
{
var bytes = System.IO.File.ReadAllBytes(fileName);
System.IO.File.Delete(fileName);
return File(bytes, contentType, fileDownloadName);
}
}
BTW, you may refrain from this method if you're dealing with very large files, and you're concerned about the memory consumption.
Create file and save it.
Response.Flush() sends all data to client.
Then you can delete temporary file.
This works for me:
FileInfo newFile = new FileInfo(Server.MapPath(tmpFile));
//create file, and save it
//...
string attachment = string.Format("attachment; filename={0}", fileName);
Response.Clear();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = fileType;
Response.WriteFile(newFile.FullName);
Response.Flush();
newFile.Delete();
Response.End();
I have posted this solution in https://stackoverflow.com/a/43561635/1726296
public ActionResult GetFile()
{
string theFilename = "<Full path your file name>"; //Your actual file name
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=<file name to be shown as download>"); //optional if you want forced download
Response.ContentType = "application/octet-stream"; //Appropriate content type based of file type
Response.WriteFile(theFilename); //Write file to response
Response.Flush(); //Flush contents
Response.End(); //Complete the response
System.IO.File.Delete(theFilename); //Delete your local file
return new EmptyResult(); //return empty action result
}