It has already been determined here that an empty using block is not an appropriate way to override Dispose()
, but what about the following case?
Is this a legitimate use for an empty using
block?
try
{
using (File.OpenRead(sourceFile)) { }
}
catch (FileNotFoundException)
{
error = "File not found: " + sourceFile;
}
catch (UnauthorizedAccessException)
{
error = "Not authorized to access file: " + sourceFile;
}
catch (Exception e)
{
error = "Error while attempting to read file: " + sourceFile + ".\n\n" + e.Message;
}
if (error != null)
return error;
System.Diagnostics.Process.Start(sourceFile);
No it's not a legitimate use for an empty using block.
You can simply write the try like this:
try
{
File.OpenRead(sourceFile).Close();
}
Either OpenRead()
will succeed and return a stream that you must close (or dispose, but I think .Close() better expresses your intent), or it will thrown an exception and not return anything.
Therefore you can always just close the returned value.
(I assume that you are just checking for read access before doing something else. However, be aware that you could in theory have a race condition because the accessibility of the file could change between you making this check and later on actually opening the file. This is unlikely to happen in practice, but you should be aware of the possibility.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With