Is Directory.Delete() / .Create() synchronous?
I also ran into this problem intermittently while running some integration tests that use the file system.
The "full" operation I wanted was to obtain an empty folder in which my process could perform its operations. The folder might already exist (with content) due to previous test runs, or it might not if either (a) the repo was freshly cloned or (b) I was adding new test cases.
Given this illuminating answer, I realized Directory.Delete
is a truly rotten plank on which to build this operation.
So I use this now:
public static DirectoryInfo EmptyDirectory(string directoryPath)
{
var directory = Directory.CreateDirectory(directoryPath);
foreach (var file in directory.EnumerateFiles())
{
file.Delete();
}
foreach (var subdirectory in directory.EnumerateDirectories())
{
subdirectory.Delete(true);
}
return directory;
}
I also submitted a suggestion at the Directory.Delete
doc page to add some kind of note about the underlying asynchronous nature of the method (at least on Windows, I guess). As far as leaky abstractions go, this is a pretty big leak.
This is an older question but worth noting - Directory.Delete
ultimately calls the RemoveDirectory
Windows function, which marks the directory as to-be-deleted, but the filesystem won't actually delete it until all file handles are closed (see docs). As a result it is perfectly possible to return from Directory.Delete
and find the directory still exists.