Why is my FileStream object being disposed of when I'm “using” a BinaryReader object?

一个人想着一个人 提交于 2019-12-23 14:36:08

问题


Consider the following function:

    private int GetSomethingFromFile(FileStream fs) 
    {
        using (BinaryReader br = new BinaryReader(fs))
        {
            fs.Seek(0, SeekOrigin.Begin);
            return br.ReadInt32();
        }
    }

A FileStream object is passed in as a parameter and a BinaryReader is declared with a using statement. When I try to use that FileStream object, after calling this function, it throws a System.ObjectDisposedException. Why is that FileStream object being disposed of along with the BinaryReader object?


回答1:


It is a very good question, and I don't know why it was decided that this was how it should be, but alas it is documented to be this way:

BinaryReader class

Close: Closes the current reader and the underlying stream.

If you check out this answer to the question How do I “fork” a Stream in .NET? then you'll see that he refers to a class called NonClosingStreamWrapper in a library called MiscUtil that @Jon Skeet has written that you can use to wrap around the stream to prevent it from being closed.

You would use it like this (for your example):

private int GetSomethingFromFile(FileStream fs) 
{
    using (var wrapper = new NonClosingStreamWrapper(fs))
    using (BinaryReader br = new BinaryReader(wrapper))
    {
        fs.Seek(0, SeekOrigin.Begin);
        return br.ReadInt32();
    }
}



回答2:


Because disposing the binary reader disposes its underlying stream.

Use "using" in the caller method instead.

The reason is arbitrary: .NET class library is implemented this way.



来源:https://stackoverflow.com/questions/5261123/why-is-my-filestream-object-being-disposed-of-when-im-using-a-binaryreader-ob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!