I have a File.Delete
in my finally clause like so:
finally
{
//remove the temporary file
if(File.Exists(transformedFile))
File.Delete(transformedFile);
}
According to the C# documentation, calling File.Delete on a nonexistent file will not throw any exceptions.
Is it okay to remove the File.Exists
wrapped, or will that expose me to possible additional exceptions?
If you need it, it's insufficient, as the file could be deleted after you confirm that it exists. In a case like this, the best practice is to simply try to delete the file. If it fails with a "file not found" type of error, then you'll know the file didn't exist. This removes an extra operation and avoids any kind of race window.
There is one situation where checking Exists
before Delete
prevents an exception. If you have a file name with an invalid path, the Exists
method returns false
.
Then it depends on what behaviour you want. In some sitations an invalid path should cause an exception.
Also, just because the file exists doesn't mean that it's always possible to delete it (at that time). You still need the exception handling for unforseen problems.
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