下载的文件,如控制器(ASP.NET MVC 3)流将自动处理? [英] The downloaded file as stream in controller (ASP.NET MVC 3) will automatically disposed?

查看:131
本文介绍了下载的文件,如控制器(ASP.NET MVC 3)流将自动处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's assume the controller which download selected file:

 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);
}

如果我用使用关键字控制器那么将引发异常: 无法访问关闭的文件

If I use using keyword in controller then the exception will be thrown: Cannot access closed file.

好吧,我想,以确保下载的文件进行处理(我不知道是否是可能的,如何做到这一点)或不?

Well, I want to be sure that downloaded file will be disposed (I don't know if is possible, how to do that) or not ?

感谢

推荐答案

Controller.File方法使用的 FileStreamResult 类里面,已经包含关键字

Controller.File method uses FileStreamResult class inside, that already contains using keyword

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);
        }
    }
}

<一个href=\"https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/SystemWebMvc/Mvc/FileStreamResult.cs\">https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/SystemWebMvc/Mvc/FileStreamResult.cs

这篇关于下载的文件,如控制器(ASP.NET MVC 3)流将自动处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆