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?
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.
}
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