3

让我们假设下载所选文件的控制器:

 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.

好吧,我想确定下载的文件是否会被处理(我不知道是否可能,怎么做)?

谢谢

4

1 回答 1

14

Controller.File 方法在内部使用FileStreamResult类,该类已经包含using关键字

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

于 2012-11-07T08:04:28.383 回答