tags:

views:

3184

answers:

7

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");
}
+21  A: 

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

Yes, thats what it's for.

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

It is safe to assume that if an object implements IDispose, that 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 IDispose.

Binary Worrier
+14  A: 

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

public void Dispose()
{
    this.Close();
}
Andrew Hare
+1  A: 

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.

Daniel Brückner
+1  A: 

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.

DrJokepu
+2  A: 

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.

Joe
+2  A: 

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.

ScottS
+1  A: 

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.