Avoiding a race in File.Exists / File.Delete or Directory.Exists / Directory.Delete

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

The above code checks if the directory exists, if so, removes it. There is a possibility that between verification exists and is deleted, that the directory has been added or deleted.

Beyond the call. Remove and discard exceptions, is there a proper way to prevent this race condition?

edit:

The reason to avoid dealing with race conditions with exception handling is because exceptions should not be used for control flow.

Is a file system lock ideal?

+4
source share
3 answers

, , dir , , , Directory.Delete , , , . , , , , :

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.
}
+3

, , Directory.Exists

if (Directory.Exists(dir))
{
    try 
    {
        Directory.Delete(dir, true);
    }
    catch (DirectoryNotFoundException e)
    {
        // do nothing, it means it doesn't exist
    }
}

/? . if, .

+3

, ​​?
, , a object singleton lock constructure?

, handle, .

, , . ​​, : , - .

? .NET . , :

IOException
, , . > --
, , , - false, - . --
. --
. --
.

UnauthorizedAccessException
.

ArgumentException
path - , . GetInvalidPathChars.

ArgumentNullException null.

PathTooLongException
, . , Windows 248 260 .

DirectoryNotFoundException
. --
(, ).

+1

All Articles