Do not do sw.Close() within the try block! If your I/O code throws an exception, your file remains open (and likely locked) until the application ends.
You can deal with such situations much better by using the using
statement.
Code example for appending a string to your file:
using (StreamWriter sw = new StreamWriter(@"Path.txt", true))
{
sw.WriteLine(write);
}
This is a C# shorthand for:
StreamWriter sw = new StreamWriter(@"Path.txt", true);
try
{
sw.WriteLine(write);
}
finally
{
sw.Close();
}
In reality, the way it is implemented, using
works with IDisposable objects. (streams implement the IDisposable interface). And using
does not call the Close() method in the implicit finally-block, but the Dispose() method. However, streams close the stream (erm...) when the Dispose() method is being called.
In short, whenever you have to control the lifetime of an IDisposable object, use using
wherever possible.
But back to topic. Exception handling... You can do the I/O exception handling within the same method, or let one of the calling methods handle the exceptions.
If the method itself should handle exceptions, do it like this:
try
{
using (StreamWriter sw = new StreamWriter(@"Path.txt", true))
{
sw.WriteLine(write);
}
}
catch (Exception ex)
{
// Exception handling here...
}
This has the advantage of the file handle already being released before the actual exception is being handled (which, when not done properly, might throw an exception too depending on what you do there).