What is the difference between StreamWriter.Flush() and StreamWriter.Close()?

StreamWriter.Flush() can be called any time you need to clear the buffer, and the stream will remain open.

StreamWriter.Close() is for closing the stream, at which point the buffer is also flushed.

But you shouldn’t really need to call either of these. Any time I see a .Close() in code I take that as a code smell, because it usually means an unexpected exception could cause the resource to be left open. What you should do, is create your StreamWriter variable in a using block, like this:

using (var writer = new StreamWriter("somefilepath.txt"))
{
   // write a bunch of stuff here
} // the streamwriter WILL be closed and flushed here, even if an exception is thrown.

Leave a Comment