Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Directory.Delete() / .Create() synchronous?

Tags:

c#

.net

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?

like image 944
Felix Avatar asked Jan 24 '16 20:01

Felix


People also ask

Which which method is used to delete directory?

The rm command removes complete directories, including subdirectories and files. The rmdir command removes empty directories.

Which method deletes the specified file?

Delete(String) is an inbuilt File class method which is used to delete the specified file.

How do I delete a file in .NET core?

To delete an uploaded file, just we need to find its path. Then we can manage to delete files with System. IO. File.


2 Answers

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.

like image 139
Owen Avatar answered Sep 30 '22 08:09

Owen


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.

like image 40
William Avatar answered Sep 30 '22 08:09

William