Home > Software design >  Recursive Deletion of Folders in C#
Recursive Deletion of Folders in C#

Time:09-30

I am trying to recursively delete all empty subdirectories in a root directory and (not files)using C#. I have referred this post (Recursive delete of files and directories in C#) and wrote the function as follows.

private void DeleteEmptySubFolders()
        {
            DirectoryInfo root = new DirectoryInfo(folderPath);
            RecursiveDelete(root,true);
           
        }
        public static void RecursiveDelete(DirectoryInfo baseDir,bool isRootDir)
        {
            if (!baseDir.Exists)
                return;

            foreach (var dir in baseDir.EnumerateDirectories())
            {
                RecursiveDelete(dir,false);
            }
            try
            {
                if (!isRootDir)
                    baseDir.Delete(false);
            }
            catch(Exception ex)
            {
                
            }
        }

My question is baseDir.Delete(false); will give me an exception when a directory is not empty, and I am just passing that exception without handling it(I just want to skip those ones, don't have to log). Is there a better way to do this?

CodePudding user response:

Instead of try/catch, check if any files exist:

bool isEmpty = !Directory.EnumerateFileSystemEntries(baseDir.FullName).Any();

Now you can avoid trying to delete non-empty folders:

if (!isRootDir && isEmpty)
    baseDir.Delete(false);
  • Related