The StreamWriter.Close() says it also closes the underlying stream of the StreamWriter. What about StreamWriter.Dispose ? Does Dispose also dispose and/or close the underlying stream
The StreamWriter.Close() says it also closes the underlying stream of the StreamWriter. What about StreamWriter.Dispose ? Does Dispose also dispose and/or close the underlying stream
StreamWriter.Close() just calls StreamWriter.Dispose() under the bonnet, so they do exactly the same thing. StreamWriter.Dispose() does close the underlying stream.
Reflector is your friend for questions like this :)
From StreamWriter.Close()
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
From TextWriter.Dispose() (which StreamWriter inherits)
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
They are thus, identical.
To quote from Framework Design Guidelines by Cwalina and Abrams in the section about the dispose pattern:
CONSIDER providing method
Close(), in addition to theDispose(), if close is standard terminology in the area.
Apparently Microsoft follow their own guidelines, and assuming this is almost always a safe bet for the .NET base class library.
The Dispose method of StreamWriter also closes the underlying stream. You can check this in the reference source here. One thing that you can do is to use a different constructor, which explicitly tells whether to close or keep the stream open. Check the leaveOpen arg:
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null)
If you plan to leave it open, then it's a good idea to pass the flag set to 'true', but then dispose the stream writer itself, so it doesn't keep a reference to the stream and potentially could dispose other resources (though it doesn't look like there are any resources besides the stream).