using System.IO;
Directory.Delete("someFolder",true);
Directory.Create("someFolder");
Will the third line be executed after the dir was deleted or while the directory is being deleted? Do I have to put the first command into a "Task" and wait until it is finished?
The rm command removes complete directories, including subdirectories and files. The rmdir command removes empty directories.
Delete(String) is an inbuilt File class method which is used to delete the specified file.
To delete an uploaded file, just we need to find its path. Then we can manage to delete files with System. IO. File.
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.
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.
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