27

How to delete a given directory recursively in C# ? A directory containing files.

Should the System.IO.Directory.Delete with the second parameter true do the trick?


EDIT:

So, I actually did answer my own question, although the answers here were a little more clarifying. The reason for me asking this in the first place was that the code that has exactly that invocation of Delete (2nd param set to true) was not doing what it was supposed to be doing. As it turned out the cause of that was that there was a file somewhere down in the the directory hierarchy with RO attribute set, and the Polish version of Windows XP was throwing a really strange message for that.

G S
  • 35,511
  • 22
  • 84
  • 118
Bartosz Radaczyński
  • 18,396
  • 14
  • 54
  • 61
  • 1
    I think you already gave the answer yourself :-) – Jakob Christensen May 29 '09 at 09:43
  • This does seem an odd question. The asker already knows about the second parameter, which is a boolean called "recursive". You're basically saying "how do I do recursive? Do I set recursive to true?" – joshcomley May 29 '09 at 09:53
  • OK, perhaps the edit clarifies. The dir contains some files... – Bartosz Radaczyński May 29 '09 at 09:57
  • 1
    I can definitely say that this method is flaky at best. I having this exact problem where I am trying to do a recursive delete on a UNC path and even though I make sure that ALL files (not directories) are deleted before hand - this method is failing. I know for a fact those folders are empty because I created them two seconds prior. No read only files situation here. – dyslexicanaboko Apr 10 '20 at 16:48

6 Answers6

33

The only solution that worked for me if the subdirectories also contains files is by using a recursive function:

    public static void RecursiveDelete(DirectoryInfo baseDir)
    {
        if (!baseDir.Exists)
            return;

        foreach (var dir in baseDir.EnumerateDirectories())
        {
            RecursiveDelete(dir);
        }
        baseDir.Delete(true);
    }

It appears that Directory.Delete(dir, true) only delete files of the current directory, and subdirectories if they are empty.

Hope it helps someone.

btw, example: RecursiveDelete( new DirectoryInfo(@"C:\my_dir") );

T.Todua
  • 53,146
  • 19
  • 236
  • 237
Jone Polvora
  • 2,184
  • 1
  • 22
  • 33
18

Yup, that's the point of that parameter. Did you try it and have any problems? (I've just double-checked, and it works fine for me.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
11

If you get UnauthorizedAccessException . You can use modified of RecursiveDelete from Jone Polvora. Thank you for Idea. I will use it.

    public static void RecursiveDelete(DirectoryInfo baseDir)
    {
        if (!baseDir.Exists)
            return;

        foreach (var dir in baseDir.EnumerateDirectories())
        {
            RecursiveDelete(dir);
        }
        var files = baseDir.GetFiles();
        foreach (var file in files)
        {
            file.IsReadOnly = false;
            file.Delete();
        }
        baseDir.Delete();
    }
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
6

Recursive works for both files and folders (oddly, I thought it didn't work for files; my bad...):

// create some nested folders...
Directory.CreateDirectory(@"c:\foo");
Directory.CreateDirectory(@"c:\foo\bar");
// ...with files...
File.WriteAllText(@"c:\foo\blap.txt", "blup");
File.WriteAllText(@"c:\foo\bar\blip.txt", "blop");
// ...and delete them
Directory.Delete(@"c:\foo", true); // fine
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I don't understand - what's the need for the 2nd parameter? Surely `Directory.Delete(@"C:\foo")` deletes `foo` and everything in it - how can you delete a directory without deleting everything in it? – Matt Arnold Dec 06 '21 at 16:22
  • 1
    @MattArnold think of it as more of a "I expect it to be empty, so if it isn't: that's a problem, please fail" vs "burn it with fire, regardless" – Marc Gravell Dec 06 '21 at 19:08
0

Modified solution from @StayOnTarget, so that root dir is not getting removed:

public static void RecursiveDelete(DirectoryInfo baseDir, bool isRootDir)
{
    if (!baseDir.Exists)
        return;
    foreach (var dir in baseDir.EnumerateDirectories()) RecursiveDelete(dir, false);
    foreach (var file in baseDir.GetFiles())
    {
        file.IsReadOnly = false;
        file.Delete();
    }
    if (!isRootDir) baseDir.Delete();
}
Rainer
  • 803
  • 10
  • 8
-1

Why do not use?

Directory.Delete(directoryPath, true);

https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx