简体   繁体   中英

Recursive Deletion of Folders in C#

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM