Does Stream.Dispose always call Stream.Close (and Stream.Flush)

C#.NetUsing

C# Problem Overview


If I have the following situation:

StreamWriter MySW = null;
try
{
   Stream MyStream = new FileStream("asdf.txt");
   MySW = new StreamWriter(MyStream);
   MySW.Write("blah");
}
finally
{
   if (MySW != null)
   {
      MySW.Flush();
      MySW.Close();
      MySW.Dispose();
   }
}

Can I just call MySW.Dispose() and skip the Close even though it is provided? Are there any Stream implimentations that don't work as expected (Like CryptoStream)?

If not, then is the following just bad code:

using (StreamWriter MySW = new StreamWriter(MyStream))
{
   MySW.Write("Blah");
}

C# Solutions


Solution 1 - C#

> Can I just call MySW.Dispose() and > skip the Close even though it is > provided?

Yes, that’s what it’s for.

> Are there any Stream implementations > that don't work as expected (Like > CryptoStream)?

It is safe to assume that if an object implements IDisposable, it will dispose of itself properly.

If it doesn’t, then that would be a bug.

> If not, then is the following just bad > code:

No, that code is the recommended way of dealing with objects that implement IDisposable.

More excellent information is in the accepted answer to Close and Dispose - which to call?

Solution 2 - C#

I used Reflector and found that System.IO.Stream.Dispose looks like this:

public void Dispose()
{
    this.Close();
}

Solution 3 - C#

As Daniel Bruckner mentioned, Dispose and Close are effectively the same thing.

However Stream does NOT call Flush() when it is disposed/closed. FileStream (and I assume any other Stream with a caching mechanism) does call Flush() when disposed.

If you are extending Stream, or MemoryStream etc. you will need to implement a call to Flush() when disposed/closed if it is necessary.

Solution 4 - C#

All standard Streams (FileStream, CryptoStream) will attempt to flush when closed/disposed. I think you can rely on this for any Microsoft stream implementations.

As a result, Close/Dispose can throw an exception if the flush fails.

In fact IIRC there was a bug in the .NET 1.0 implementation of FileStream in that it would fail to release the file handle if the flush throws an exception. This was fixed in .NET 1.1 by adding a try/finally block to the Dispose(boolean) method.

Solution 5 - C#

Both StreamWriter.Dispose() and Stream.Dispose() release all resources held by the objects. Both of them close the underlying stream.

The source code of Stream.Dispose() (note that this is implementation details so don't rely on it):

public void Dispose()
{
    this.Close();
}

StreamWriter.Dispose() (same as with Stream.Dispose()):

protected override void Dispose(bool disposing)
{
    try
    {
        // Not relevant things
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            try
            {
                if (disposing)
                {
                    this.stream.Close();
                }
            }
            finally
            {
                // Not relevant things
            }
        }
    }
}

Still, I usually implicitly close streams/streamwriters before disposing them - I think it looks cleaner.

Solution 6 - C#

For objects that need to be manually closed, every effort should be made to create the object in a using block.

//Cannot access 'stream'
using (FileStream stream = File.Open ("c:\\test.bin"))
{
   //Do work on 'stream'
} // 'stream' is closed and disposed of even if there is an exception escaping this block
// Cannot access 'stream' 

In this way one can never incorrectly access 'stream' out of the context of the using clause and the file is always closed.

Solution 7 - C#

I looked in the .net source for the Stream class, it had the following which would suggest that yes you can...

    // Stream used to require that all cleanup logic went into Close(),
    // which was thought up before we invented IDisposable.  However, we 
    // need to follow the IDisposable pattern so that users can write
    // sensible subclasses without needing to inspect all their base
    // classes, and without worrying about version brittleness, from a
    // base class switching to the Dispose pattern.  We're moving 
    // Stream to the Dispose(bool) pattern - that's where all subclasses
    // should put their cleanup starting in V2. 
    public virtual void Close() 
    {
        Dispose(true); 
        GC.SuppressFinalize(this);
    }

    public void Dispose() 
    {
        Close(); 
    } 

Solution 8 - C#

Stream.Close is implemented by a call to Stream.Dispose or vice versa - so the methods are equivalent. Stream.Close exists just because closing a stream sounds more natural than disposing a stream.

Besides you should try to avoid explicit calls to this methods and use the using statement instead in order to get correct exception handling for free.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasonRShaverView Question on Stackoverflow
Solution 1 - C#Binary WorrierView Answer on Stackoverflow
Solution 2 - C#Andrew HareView Answer on Stackoverflow
Solution 3 - C#ScottSView Answer on Stackoverflow
Solution 4 - C#JoeView Answer on Stackoverflow
Solution 5 - C#Tamas CzinegeView Answer on Stackoverflow
Solution 6 - C#clemahieuView Answer on Stackoverflow
Solution 7 - C#Steve SheldonView Answer on Stackoverflow
Solution 8 - C#Daniel BrücknerView Answer on Stackoverflow