1

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?

Soumya
  • 323
  • 1
  • 5
  • 16
  • 6
    https://stackoverflow.com/questions/2811509/c-sharp-remove-all-empty-subdirectories – Ralf Sep 29 '22 at 15:14
  • 2
    Does this answer your question? [C# Remove all empty subdirectories](https://stackoverflow.com/questions/2811509/c-sharp-remove-all-empty-subdirectories) – Codingwiz Sep 29 '22 at 16:34

1 Answers1

2

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);
Soumya
  • 323
  • 1
  • 5
  • 16
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you so much. Since my baseDir is of type DirectoryInfo `bool isEmpty = !Directory.EnumerateFileSystemEntries(baseDir.FullName).Any();` works. Can you please edit the answer? – Soumya Sep 30 '22 at 08:09