Did you ever write a code like this:
Of course not. It should look like
The difference is that the first sample doesn’t invoke Close() or Dispose() on StreamWriter while the later does. Needless to say that you have to call them (Dispose is enough as implicitly calls Close if necessary) and the first sample might result in loss of data because StreamWriter implements buffered write that is flushed on Close.
But still it might happen even to you that you forget to Close the StreamWriter (I know, I know it won’t happen to you, but just in case). The good news is that VS2005 will help you to find this bug through one of its so called Managed Debugging Assistants (MDA) named StreamWriterBufferDataLost. MDAs are watching your code for various kinds of bugs while it executes. Find more about MDAs in this excellent MSDN Magazine article. Anyway StreamWriterBufferDataLost MDA isn’t turned on by default – you have to turn it on explicitly: open Debug/Exceptions window and expand Managed Debugging Assistants node.
That’s it. Next time debugger steps over such bug you’ll get this nice exception:
A StreamWriter was not closed and all buffered data within that StreamWriter was not flushed to the underlying stream. (This was detected when the StreamWriter was finalized with data in its buffer.) A portion of the data was lost. Consider one of calling Close(), Flush(), setting the StreamWriter’s AutoFlush property to true, or allocating the StreamWriter with a “using” statement.Having exception right at the time instead of seeing some strange behaviour here and there is of tremendous help, isn’t.
And I am pretty sure that few people noticed these precious helpers. So now you know – use them and they’ll help you a lot.