The problem is that you can only delete a file after it has been written in the response, and the file is written by FileStreamResult only after it has been returned from the action.
One way to handle this is to create a subclass of FileResult that will delete the file.
This is easier for the FilePathResult subclass FilePathResult that the class has access to the file name.
public class FilePathWithDeleteResult : FilePathResult { public FilePathResult(string fileName, string contentType) : base(string fileName, string contentType) { } protected override void WriteFile(HttpResponseBase response) { base.WriteFile(response); File.Delete(FileName); Directory.Delete(FileName); } }
Note. I have not tested the above. Remove all errors before use.
Now change the controller code to something like:
public ActionResult DownloadProjects () { Directory.CreateDirectory(_tempDirectory); // temporary file is created here _zipFile.Save(_tempDirectory + _tempFileName); return new FilePathWithDeleteResult(_tempDirectory + _tempFileName, "application/zip") { FileDownloadName = "Projects.zip" }; }
hwiechers
source share