我在c# MVC应用程序中有一个函数,它创建了一个临时目录和一个临时文件,然后使用FileStream打开该文件,将FileStream返回给调用函数,然后需要删除临时文件。但是,我不知道如何删除临时目录和文件,因为它总是错误地说"该进程无法访问文件,因为它正在被另一个进程使用"。这就是我所尝试的,但是FileStream仍然在最后块中使用临时文件。如何返回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时,我得到一个系统内存不足的异常。
以下是我使用的上述内容的精简版本:
public class DeleteAfterReadingStream : FileStream
{
public DeleteAfterReadingStream(string path)
: base(path, FileMode.Open)
{
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (File.Exists(Name))
File.Delete(Name);
}
}
您可以创建一个包装器类来实现Stream
合约,并在内部包含FileStream
,以及维护到文件的路径。
所有标准的Stream
方法和属性都将被传递给FileStream
实例。
当这个包装器类是Dispose
d时,您将(在Dispose
之后包装的FileStream
)然后删除文件。
我采纳了Damien_The_Unbeliever的建议,并将其写了下来,效果非常好。我只是想分享一下这个课程:
public class BurnAfterReadingFileStream : Stream
{
private FileStream fs;
public BurnAfterReadingFileStream(string path) { fs = System.IO.File.OpenRead(path); }
public override bool CanRead { get { return fs.CanRead; } }
public override bool CanSeek { get { return fs.CanRead; } }
public override bool CanWrite { get { return fs.CanRead; } }
public override void Flush() { fs.Flush(); }
public override long Length { get { return fs.Length; } }
public override long Position { get { return fs.Position; } set { fs.Position = value; } }
public override int Read(byte[] buffer, int offset, int count) { return fs.Read(buffer, offset, count); }
public override long Seek(long offset, SeekOrigin origin) { return fs.Seek(offset, origin); }
public override void SetLength(long value) { fs.SetLength(value); }
public override void Write(byte[] buffer, int offset, int count) { fs.Write(buffer, offset, count); }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (Position > 0) //web service quickly disposes the object (with the position at 0), but it must get rebuilt and re-disposed when the client reads it (when the position is not zero)
{
fs.Close();
if (System.IO.File.Exists(fs.Name))
try { System.IO.File.Delete(fs.Name); }
finally { }
}
}
}
问题是您只能在将文件写入响应之后删除该文件,并且文件只有在从操作返回后才由FileStreamResult写入。
一种处理方法是创建FileResult的子类来删除文件。
更容易子类化FilePathResult
,这样类就可以访问文件名。
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);
}
}
注意:我还没有测试上面的内容。
现在将控制器代码更改为:
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建议的方法,但使其工作的唯一方法是在删除文件之前关闭响应流。
这是源代码,请注意,我在删除流之前刷新了它。
public class FilePathAutoDeleteResult : FilePathResult
{
public FilePathAutoDeleteResult(string fileName, string contentType) : base(fileName, contentType)
{
}
protected override void WriteFile(HttpResponseBase response)
{
base.WriteFile(response);
response.Flush();
File.Delete(FileName);
}
}
控制器应该这样调用它:
public ActionResult DownloadFile() {
var tempFile = Path.GetTempFileName();
//do your file processing here...
//For example: generate a pdf file
return new FilePathAutoDeleteResult(tempFile, "application/pdf")
{
FileDownloadName = "Awesome pdf file.pdf"
};
}