Recursive delete of files and directories in C#

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") );


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.)


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();
    }

Tags:

C#