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()
{
Directory.CreateDirectory(_tempDirectory);
// temporary file is created here
_zipFile.Save(_tempDirectory + _tempFileName);
try
{
FileStream stream = new FileStream(_tempDirectory + _tempFileName, FileMode.Open);
return stream;
}
finally
{
File.Delete(_tempDirectory + _tempFileName);
Directory.Delete(_tempDirectory);
}
}
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.
FileStream
has the file open, why do you even expect to be able to delete the file? That would make the returnedFileStream
unusable.MemoryStream
is horribly inefficient in terms of memory usage for large files, especially if the target only needs to process the file instead of reading it all in; and if it does need to read it all in, it would result in double memory usage.