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.
Pseudocode:
outputWriter = New StreamWriter(filepath, False, Encoding.Default)
Try
For Each lineOfText in textLines
Try
outputWriter.WriteLine(lineOfText)
Catch ex As ApplicationException
ex.Add(“Failed writing line”,lineOfText)
Throw ex
End Try
Next
Finally
outputWriter.Close
End Try
[…] The upside of all this is that I have (re-)learned some valuable lessons about error handling when writing to text streams using VB.Net. […]