Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid race in File.Exists/File.Delete or Directory.Exists/Directory.Delete

Tags:

.net

file-io

if (Directory.Exists(dir))
    Directory.Delete(dir, true);

The above code checks if the directory exists, if so, deletes it. There's the chance that between the exists check and the delete, that the directory was added or removed.

Aside from calling .Delete and throwing away the exceptions, is there a proper way to prevent this race condition?

edit:

The reason to avoid battling the race condition with exception handling is because exceptions should not be used for control flow.

An ideal solution would be a file system lock of some sorts?

like image 439
Joseph Lennox Avatar asked Feb 12 '23 01:02

Joseph Lennox


1 Answers

If the desired end result is to ensure that the directory dir does not exist, regardless of whether it existed or not, then you should call Directory.Delete and catch any exception it may throw, without bothering to check if the directory exists or not. Then you should check if the directory exists to see if you are good to go, or if your operation has failed for some other reason:

try {
    Directory.Delete(dir, true);
} catch {
    // Ignore any exceptions
}
if (Directory.Exists(dir)) {
    // The above has failed to delete the directory.
    // This is the situation to which your program probably wants to react.
}
like image 175
Sergey Kalinichenko Avatar answered Feb 14 '23 13:02

Sergey Kalinichenko