Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call File.Exists before calling File.Delete?

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?

like image 272
Codeman Avatar asked Jan 19 '13 01:01

Codeman


2 Answers

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.

like image 130
David Schwartz Avatar answered Oct 14 '22 15:10

David Schwartz


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.

like image 43
Guffa Avatar answered Oct 14 '22 14:10

Guffa