I have a function in a C# MVC application that creates a temporary directory and a temporary file, then opens the file using FileStream, returns the FileStream to a calling function, and then needs to delete the temporary files. However, I do not know how to delete the temp directory and file because it always errors out saying "the process cannot access the file because it is being used by another process." This is what I tried, but the FileStream is still using the temp file in the finally block. How can I return the FileStream and delete the temporary files?
public FileStream DownloadProjectsZipFileStream()
// temporary file is created here
_zipFile.Save(_tempDirectory + _tempFileName);
FileStream stream = new FileStream(_tempDirectory + _tempFileName, FileMode.Open);
File.Delete(_tempDirectory + _tempFileName);
public ActionResult DownloadProjects ()
ProjectDownloader projectDownloader = new ProjectDownloader();
FileStream stream = projectDownloader.DownloadProjectsZipFileStream();
return File(stream, "application/zip", "Projects.zip");
You could create a wrapper class that implements the
Stream contract and that contains the
FileStream internally, as well as maintaining the path to the file.
All of the standard
Stream methods and properties would just be passed to the
When this wrapper class is
Disposed, you would (after
Disposeing the wrapped
FileStream) then delete the file.