【问题标题】:The downloaded file as stream in controller (ASP.NET MVC 3) will automatically disposed?下载的文件作为控制器(ASP.NET MVC 3)中的流将自动处理?
【发布时间】:2012-10-27 06:05:07
【问题描述】:

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

 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

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

谢谢

【问题讨论】:

    标签: c# asp.net-mvc-3 stream


    【解决方案1】:

    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

    【讨论】:

    • 如果我在DownloadFiles 上进行集成测试,那么将失败。为什么我不能在模型中使用 dispose(因为给我无法访问已关闭的文件)。
    • MVC ActionResult 在您离开操作方法后执行。 FileStreamResult 需要打开流,因为它从流中读取。所以你不应该在你的 action 方法中关闭一个流。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多