Is your code the only thing that can delete or add such folder?
If so, why don't you just add the critical section to your code, like a object
singleton and lock
constructure?
If you want to avoid deleting an already deleted folder, you can add a process handle
for it so other processes can't destroy it.
If you want to avoid a situation where this code wouldn't delete needed directory, I can't imagine a good solution for this. Imagine the situation as: your code runs, and after it finishes, somebody re-creates the folder.
Why not just catch the specific exception in this case? It's a natural way in .NET to handle unexpected situations. There are a lot of situations you can't predict:
Exceptions
IOException
A file with the same name and location specified by path exists.
-or-
The directory specified by path is read-only, or recursive is false and path is not an empty directory.
-or-
The directory is the application's current working directory.
-or-
The directory contains a read-only file.
-or-
The directory is being used by another process.
UnauthorizedAccessException
The caller does not have the required permission.
ArgumentException
path is a zero-length string, contains
only white space, or contains one or more invalid characters. You can
query for invalid characters by using the GetInvalidPathChars
method.
ArgumentNullException
path is null.
PathTooLongException
The specified path, file name, or both exceed the system-defined maximum
length. For example, on Windows-based platforms, paths must be less
than 248
characters and file names must be less than 260
characters.
DirectoryNotFoundException
path does not exist or could not be found.
-or-
The specified path is invalid (for example, it is on an unmapped drive).