I have very weird behavior. I have,
Directory.Delete(tempFolder, true);
if (Directory.Exists(tempFolder))
{
}
Sometimes Directory.Exists return true. Why? May be the explorer is open?
Directory.Delete
calls the Windows API function RemoveDirectory
. The observed behavior is documented:
The
RemoveDirectory
function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.
The .NET documentation is unfortunately missing this information. Whether the static Directory.Delete
method opens a handle to the directory is not documented. Likewise, if it does, it is not documented when the handle is closed.
Without any of this information, the best you can do is to poll for completion:
Directory.Delete(tempFolder, true);
while (Directory.Exists(tempFolder)) Thread.Sleep(0);
// At this point the directory has been removed from the filesystem
Even though polling should generally be avoided in preference of events, installing a filesystem watcher would be a bit over the top for this. Still, keep in mind, that this operation does not come for free, particularly when dealing with a network drive.
This information, however, does not help in finding a better solution than the one described above (polling for completion).
GC.Collect()
does not run finalizers. This, too, appears to work by buying extra time.