一時ディレクトリと一時ファイルを作成し、FileStream を使用してファイルを開き、呼び出し元の関数に FileStream を返し、一時ファイルを削除する必要がある C# MVC アプリケーションの関数があります。ただし、「別のプロセスが使用しているため、プロセスはファイルにアクセスできません」と常にエラーになるため、一時ディレクトリとファイルを削除する方法がわかりません。これは私が試したものですが、FileStream はまだ finally ブロックで一時ファイルを使用しています。FileStream を返して一時ファイルを削除するにはどうすればよいですか?
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);
}
}
FileStream が返される関数は次のようになります。
public ActionResult DownloadProjects ()
{
ProjectDownloader projectDownloader = new ProjectDownloader();
FileStream stream = projectDownloader.DownloadProjectsZipFileStream();
return File(stream, "application/zip", "Projects.zip");
}
更新: zip ファイルが 380 MB であることを忘れていました。MemoryStream を使用すると、システムのメモリ不足例外が発生します。