【问题标题】:Does FileStreamResult close Stream?FileStreamResult 是否关闭 Stream?
【发布时间】:2014-12-04 05:26:44
【问题描述】:

我的问题类似于这个问题: 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 自动关闭吗?谢谢!

【问题讨论】:

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


    【解决方案1】:

    是的。它在流周围使用using 块,确保资源会被释放。

    这里是FileStreamResultWriteFile方法的内部implementation

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

    【讨论】:

    • 谢谢!只是好奇,你在哪里找到的? Andrei 链接到 MVC 3 的代码;你的看起来像另一个版本。
    • 这是 MVC5 最新版本。我得到了带有反编译器的代码,但你可以在 codeplex 上找到实际代码,它也包括 cmets ;)
    • 在 MVC6 (vNext) 流is being closed too
    • 现在移动here
    猜你喜欢
    • 2015-08-31
    • 2012-05-12
    • 2010-11-02
    • 2020-08-05
    • 2010-12-15
    • 2012-12-06
    • 2019-06-20
    相关资源
    最近更新 更多