FileStreamResult是否关闭Stream?

时间:2014-10-09 10:11:23

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

我的问题类似于这个问题: Does File() In asp.net mvc close the stream?

我在C#MVC 4中有以下内容。

FileStream fs = new FileStream(pathToFileOnDisk, FileMode.Open);
FileStreamResult fsResult = new FileStreamResult(fs, "Text");
return fsResult;

fs会自动关闭FileStreamResult吗?谢谢!

1 个答案:

答案 0 :(得分:30)

是。它在流周围使用using块,确保资源将被处置。

以下是FileStreamResult WriteFile方法的内部实现:

protected override void WriteFile(HttpResponseBase response)
{
    Stream outputStream = response.OutputStream;
    using (this.FileStream)
    {
        byte[] buffer = new byte[0x1000];
        while (true)
        {
            int count = this.FileStream.Read(buffer, 0, 0x1000);
            if (count == 0)
            {
                return;
            }
            outputStream.Write(buffer, 0, count);
        }
    }
}