Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Folder if it is Empty using C#

Tags:

c#

directory

I am writing a tool that will allow me to go though a fairly large list of Directories and Sub-directories. I would like it to delete a folder if there it is empty. I can delete folders and sub folders that are empty with this code:

string dir = textBox1.Text;
string[] folders = System.IO.Directory.GetDirectories(dir, "*.*", System.IO.SearchOption.AllDirectories);
foreach (var directory in folders)
{
    if (System.IO.Directory.GetFiles(directory).Length == 0 && System.IO.Directory.GetDirectories(directory).Length == 0)
    {
        System.IO.StreamWriter Dfile = new System.IO.StreamWriter(newpath, true);
        System.IO.Directory.Delete(directory);
    }
}

My question is how to have the code go though and check the folders after each delete because once it deletes a folder it could make the parent folder empty and should then should be deleted. Once the code does not find any folders or sub-folders that are empty it would exit.

like image 610
Eddie Hunter Avatar asked Aug 17 '26 02:08

Eddie Hunter


1 Answers

Write a depth-first recursive function. As you complete each recursive call, check the current folder to see if it is empty. If it is, then delete it.

Something like this (pseudocode)

DeleteEmptyFolders(path)
{
  foreach Folder f in Path
  {
    DeleteEmptyFolders(f);

    if (f is empty)
    {
       Delete(f);
    }
  }
}
like image 85
Jason Avatar answered Aug 18 '26 17:08

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!