alumb
alumb

Reputation: 4441

.Net MVC Return file and then delete it

I've produced a MVC app that when you access /App/export it zips up all the files in a particular folder and then returns the zip file. The code looks something like:

public ActionResult Export() {
    exporter = new Project.Exporter("/mypath/")
    return File(exporter.filePath, "application/zip", exporter.fileName);
}

What I would like to do is return the file to the user and then delete it. Is there any way to set a timeout to delete the file? or hold onto the file handle so the file isn't deleted till after the request is finished?

Upvotes: 2

Views: 3457

Answers (3)

Ahmed OSama
Ahmed OSama

Reputation: 43

I know this thread is too old , but here is a solution if someone still faces this.

  1. create temp file normally.

  2. Read file into bytes array in memory by System.IO.File.ReadAllBytes().

  3. Delete file from desk.

  4. Return the file bytes by File(byte[] ,"application/zip" ,"SomeNAme.zip") , this is from your controller. Code Sample here:

         //Load ZipFile
         var toDownload = System.IO.File.ReadAllBytes(zipFile);
         //Clean Files
         Directory.Delete(tmpFolder, true);
         System.IO.File.Delete(zipFile);
    
         //Return result for download
         return File(toDownload,"application/zip",$"Certificates_{rs}.zip");
    

Upvotes: 1

Dunc
Dunc

Reputation: 18942

You could create a Stream implementation similar to FileStream, but which deletes the file when it is disposed.

There's some good code in this SO post.

Upvotes: -1

rsenna
rsenna

Reputation: 11982

Sorry, I do not have the code right now...

But the idea here is: just avoid creating a temporary file! You may write the zipped data directly to the response, using a MemoryStream for that.

EDIT Something on that line (it's not using MemoryStream but the idea is the same, avoiding creating a temp file, here using the DotNetZip library):

DotNetZip now can save directly to ASP.NET Response.OutputStream.

Upvotes: 7

Related Questions