Herein are some tips on error handling when using the .Net StreamWriter.
If you write text to disk using a .Net streamwriter, then the data is buffered to memory before it is actually flushed to disk. If the stream is not closed properly, the output file will be truncated. This can happen if the application writing the stream encounters an error.
The solution is to wrap the data-writes in a Try…Finally block to ensure that the buffer is actually written before the application terminates.
It can also be useful to wrap every write in a Try…Catch block so that context information can be added to the error message in the event of the applicaion failing.
Finally, the Flush method can be called to flush the contents of the stream’s buffer to disk at any time before the Close method is called.
outputWriter = New StreamWriter(filepath, False, Encoding.Default)
For Each lineOfText in textLines
Catch ex As ApplicationException
ex.Add(“Failed writing line”,lineOfText)