Cannot delete directory with Directory.Delete(path, true)

I’m using .NET 3.5, trying to recursively delete a directory using:

Directory.Delete(myPath, true);

My understanding is that this should throw if files are in use or there is a permissions problem, but otherwise it should delete the directory and all of its contents.

However, I occasionally get this:

System.IO.IOException: The directory is not empty.
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
    at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
    ...

I’m not surprised that the method sometimes throws, but I’m surprised to get this particular message when recursive is true. (I know the directory is not empty.)

Is there a reason I’d see this instead of AccessViolationException?

27 Answers
27

Leave a Comment