Bumper Bumper - 1 month ago 6x
C# Question

Can't delete temporary files after returning FileStream

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);
return stream;
File.Delete(_tempDirectory + _tempFileName);

The function the FileStream is returned to looks like this:

public ActionResult DownloadProjects ()
ProjectDownloader projectDownloader = new ProjectDownloader();

FileStream stream = projectDownloader.DownloadProjectsZipFileStream();
return File(stream, "application/zip", "Projects.zip");

Update: I forgot to mention the zip file is 380 MB. I get a system out of memory exception when using a MemoryStream.


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 FileStream instance.

When this wrapper class is Disposed, you would (after Disposeing the wrapped FileStream) then delete the file.