2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
alumb
  • 4,401
  • 8
  • 42
  • 52

3 Answers3

7

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.

Community
  • 1
  • 1
rsenna
  • 11,775
  • 1
  • 54
  • 60
  • data i am returning is so huge that it is cannot be in memory so have to create a temp file – PUG Jun 18 '13 at 19:28
  • @jaminator: So do it. But in that case, I would create an external job for deleting old temporary files. – rsenna Jun 18 '13 at 20:52
1

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");
    
-1

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.

Community
  • 1
  • 1
Dunc
  • 18,404
  • 6
  • 86
  • 103