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

Solution 1:

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.

Solution 2:

StreamWriter.Flush() will flush anything in the Stream out to the file. This can be done in the middle of using the Stream and you can continue to write.

StreamWriter.Close() closes the Stream for writing. This includes Flushing the Stream one last time.

There's a better way to do things though. Since StreamWriter implements IDisposable, you can wrap the StreamWriter in a using block.

using(StreamWriter sw = new StreamWriter(stream))
{
     // Work with things here
}

After the using block, Dispose will be called...which will Flush and Close the Stream for you.

Solution 3:

I had a case where I was writing a very long string to a StreamWriter with an underlying MemoryStream. The MemoryStream was being consumed by something else before the writer and the stream were disposed.

using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream , Encoding.UTF8))
{
    streamWriter.Write(someRealyLongStringValue);
    DoSomethingWithTheStream(memoryStream );
}

With really long strings the end of the string was being truncated. This was resolved by calling flush before the stream was used. Alternatively I could have set AutoFlush to true.

Solution 4:

From MSDN:

Flush: Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Close: Closes the current StreamWriter object and the underlying stream.