The suggestion to utilize the using
statement is a good one; but it isn't your only choice. It just tends to be preferred by developers for its syntactically "clean" look and ease of use.
The main thing (and what using
always ensures for you) is to make sure that you are calling FileStream.Close
no matter what. If you hit an exception, this code might be missed. Therefore at the very least put your call to Close
in a finally
block.
Personally, if I'm writing any error handling myself, I prefer try
/catch
/finally
to try
/using
/catch
. Another scenario in which I much prefer using finally
is where I'm working with multiple IDisposable
objects, and I want to avoid deep nesting. Consider the following code:
try {
using (DisposableObject obj1 = GetDisposableObject()) {
// do something
using (DisposableObject obj2 = GetAnotherDisposableObject()) {
// do something else
using (DisposableObject obj3 = GetYetAnotherDisposableObject()) {
// do even more things
// this code is now quite nested
}
}
}
} catch (SomeException ex) {
// some error-handling magic
}
Now compare that to this:
DisposableObject obj1 = null;
DisposableObject obj2 = null;
DisposableObject obj3 = null;
try {
obj1 = GetDisposableObject();
// do something
obj2 = GetAnotherDisposableObject();
// do something else
obj3 = GetYetAnotherDisposableObject();
// do even more things
// this code doesn't have to be nested
} catch (SomeException ex) {
// some error-handling magic
} finally {
if (obj3 != null) obj3.Dispose();
if (obj2 != null) obj2.Dispose();
if (obj1 != null) obj1.Dispose();
}
Personally, I find the latter to be much more readable.
Obviously, this is a personal preference. The above two code samples achieve the same result.