Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete file after download with ASP.NET MVC?

Tags:

c#

asp.net-mvc

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?

like image 593
Valentin V Avatar asked Jan 11 '10 12:01

Valentin V


People also ask

How can we delete a file in C#?

The File. Delete(path) method is used to delete a file in C#. The File. Delete() method takes the full path (absolute path including the file name) of the file to be deleted.


3 Answers

You can return just regular FileStreamResult which is opened with FileOptions.DeleteOnClose. File stream will be disposed with result by asp.net. This answer dosen't require usage of low level response methods which may backfire in certain situations. Also no extra work will be done like loading file to memory as whole.

var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
return File(
    fileStream: fs,
    contentType: System.Net.Mime.MediaTypeNames.Application.Octet,
    fileDownloadName: "File.abc");

This answer is based on answer by Alan West and comment by Thariq Nugrohotomo.

like image 195
Risord Avatar answered Oct 23 '22 01:10

Risord


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.

like image 36
Alan West Avatar answered Oct 23 '22 03:10

Alan West


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();
like image 35
biesiad Avatar answered Oct 23 '22 03:10

biesiad