让我们假设其下载所选文件控制器:
public FileResult Download( string f ) {
Stream file = MyModel.DownloadFiles( f );
return File( file, "application/octet-stream", (file as FileStream).Name );
}
和MyModel包含
public static Stream DownloadFiles(string file){
return new FileStream(file, FileMode.Open, FileAccess.Read);
}
如果我用using
在控制器那么将引发异常关键字: Cannot access closed file
。
嗯,我想,以确保下载的文件将设置(我不知道是否是可能的,如何做到这一点),或不?
谢谢
Controller.File方法使用FileStreamResult类里面,已经包含使用关键字
protected override void WriteFile(HttpResponseBase response) {
// grab chunks of data and write to the output stream
Stream outputStream = response.OutputStream;
using (FileStream) {
byte[] buffer = new byte[_bufferSize];
while (true) {
int bytesRead = FileStream.Read(buffer, 0, _bufferSize);
if (bytesRead == 0) {
// no more data
break;
}
outputStream.Write(buffer, 0, bytesRead);
}
}
}
https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/SystemWebMvc/Mvc/FileStreamResult.cs
文章来源: The downloaded file as stream in controller (ASP.NET MVC 3) will automatically disposed?