12

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?

1

6 Answers 6

14

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.

3
  • Good point on the race condition. This should never happen in my code, but we all know what happens with things that "should never happen".
    – Codeman
    Jan 19, 2013 at 1:29
  • 1
    Right. The race condition is the general reason not to do this. It's also just not needed. Jan 19, 2013 at 1:47
  • Of course the file might still be re-created by someone else after you call delete, so there might still be a race condition for your other code...
    – AyCe
    Apr 10, 2019 at 12:45
10

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.

1
  • I'm not too concerned about files staying there, and the exception should bubble up to our logging layer (plus I really don't want a try/catch in my finally). Thanks!
    – Codeman
    Jan 19, 2013 at 1:31
5

File.Delete does not throw a FileNotFoundException, it does not care. It will throw an exception only if the path is invalid, as in it has directories that do not exist, in that case it will throw DirectoryNotFoundException.

This code won't throw any exception.

var file = new FileInfo(@"C:\doesnotexist.file11111");
file.Delete();

This will throw DirectoryNotFoundException

var file = new FileInfo(@"C:\bad.dir\doesnotexist.file11111");
file.Delete();

MSDN File.Delete

1

Let's look at this logically and critically. Assuming the MSDN doco isn't 100% accurate (it does contain occassional errors) and a FileNotFoundException could be thrown, it would caused by either :

  1. the file never existed to begin with (you exited the try and entered the finally before the file was created)

  2. you have a programmatic error (you've assembled the file path or name incorrectly)

One would assume that option #2 shouldn't happen, because you test for that, if it can still happen then you have smelly code. That leaves option #1 as the only viable option, in which case you don't care about the exception, so you would just catch it and move on. This means your specific question is largely redundant even if a FileNotFoundException could be thrown.

However...
I would still wrap the File.Delete with a try/catch because IMVHO there are still two exceptions that are possible and you need to take notice of: IOException and UnauthorizedAccessException. If either of those occur you should look at some sort of mitigation (maybe set up the file for deletion upon next reboot and/or notify the user in some way).

2
  • 1
    While I don't disagree that the MSDN documentation isn't 100% accurate, in this situation it is correct. File.Delete() does not throw any exceptions if the file does not exist.
    – myermian
    Jan 19, 2013 at 1:33
  • 1
    @m-y Yes it's a hypothetical situation, but I'm trying to help the OP analyze something like this for themselves, analytical thinking is a critical part of programming. In any case all the other answers (so far) concentrated on the FileNotFound issue and forgot the second part of the question...
    – slugster
    Jan 19, 2013 at 1:37
1

you still can get other type of exceptions. for example IOException if file is in used.

so if you insist to delete file in finally block and want to be sure of not getting exception just put another try-catch around File.delete.

finally
{
   try 
   {
     //remove the temporary file
     File.Delete(transformedFile);
   }
   catch
   {
   }
}

but if your goal is to delete file in any case, I think it would be good idea if you open file exclusively and in this case you should close file first and then delete it.

0

I've asked a similar question to this question before, and I came to this conclusion:

It depends. Yes, I know... not really a straightforward answer, but here are a few notes to take to determine if your situation requires a file exists check and/or a try { ... } catch { ... } block around the File.Delete(...) method.

  • Did your code generate the file? If so, you don't really need to do the check to see if the file exists.
  • Do you care about handling other issues? Remember, you are working with a file system, and the MSDN documentation clearly shows you that the method could generate exceptions due to other circumstances.
1
  • Yes, I probably want other Exceptions to just bubble up, and I don't want to catch them.
    – Codeman
    Jan 19, 2013 at 1:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.