Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing FileStream and BinaryReader

Tags:

c#

.net

I have a class which manages access to a binary file. I want to open this file on first request and then keep it open until the instance of my class gets disposed. I have implemented it like so:

public class SomeService : IDisposable
{
    private BinaryReader _reader;

    public int ServiceFunction(...)
    {
        if (_reader == null)
            CreateReader();

        // Do something with _reader and return a result
    }

    private void CreateReader()
    {
        var stream = new FileStream("myFile", FileMode.Open, FileAccess.Read);
        _reader = new BinaryReader(stream);
    }

    public void Dispose()
    {
        if (_reader != null)
            _reader.Dispose();
    }
}

I would then use the class this way:

using (var service = new SomeService())
{
    foreach (var item in someList)
    {
        // other stuff
        if (eventuallyTrue)
        {
            int result = service.ServiceFunction(item.SomeProperty);
            // other stuff
        }
    }
}

Questions:

  • Is it enough to call _reader.Dispose() or is it also necessary to dispose the FileStream explicitely?
  • If I need to dispose the FileStream too, can I modify the Dispose method like this:

    public void Dispose()
    {
        if (_reader != null)
        {
            if (_reader.BaseStream != null)
                _reader.BaseStream.Dispose();
            _reader.Dispose();
            // Does the order of disposing matter here ?
        }
    }
    
  • Or do I need to hold the FileStream in a separate class variable private FileStream _stream and dispose this stream later?

like image 929
Slauma Avatar asked Mar 02 '26 03:03

Slauma


1 Answers

Disposing of the _reader is enough.

But that is because of a peculiar 'feature' of the reader, it assumes ownership of the stream.

So as a general pattern for 2 related or unrelated Disposables it will not do. And therefore I would store the Stream as _stream and Dispose it in the end too, just to be safe and consistent. It certainly won't hurt.

like image 142
Henk Holterman Avatar answered Mar 04 '26 16:03

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!