StreamWriter and Error Handling

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

Advertisements

One Response to StreamWriter and Error Handling

  1. […] 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. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: