Click here to Skip to main content
Click here to Skip to main content
Go to top

Blank Folder Remover from Selected Path using Recursion

, 29 Mar 2013
Rate this:
Please Sign up or sign in to vote.
Blank folder remover from selected path using recursion.

Introduction

Because if somebody wants to delete only the blank folders from the specific path and at that path there are many number of folders available then it will be the trivial thing for the user. 

So for the user's easyness I implement this small application which will remove all blank folders from the selected path.

Background

The main concept in this application is RECURSION.

I use the recursion to perform this task. Also give the GUI for user to set number of recursion.

So, suppose user set '5' recursion number then it will check and delete the folders 5 times means 5 recursion will occurre.

Using the code 

public XElement GetDirectoryXml(DirectoryInfo dir)
{
    var info = new XElement("DIRECTORY", new XAttribute("NAME", dir.Name),
        new XAttribute("PATH", dir.ToString()),
        new XAttribute("DIRECTORYCOUNT", Directory.GetDirectories(dir.ToString()).Count()),
        new XAttribute("FILECOUNT", Directory.GetFiles(dir.ToString()).Count()));

    foreach (var file in dir.GetFiles())
        info.Add(new XElement("FILE", new XAttribute("NAME", file.Name),
            new XAttribute("PATH", file.DirectoryName + @"\" + file.ToString())));
    
    foreach (string subDir in Directory.GetDirectories(dir.ToString()))
        info.Add(GetDirectoryXml(new DirectoryInfo(subDir)));

    return info;
}
public void ConvertXMLToDataSet(string xmlData)
{
    StringReader stream = null;
    System.Xml.XmlTextReader reader = null;
    try
    {
        DataSet xmlDS = new DataSet();
        stream = new StringReader(xmlData);
        reader = new System.Xml.XmlTextReader(stream);
        xmlDS.ReadXml(reader);

        RemoveEmptyFolders(xmlDS.Tables["DIRECTORY"]);
    }
    catch {}
    finally
    {
        if (reader != null) reader.Close();
    }
}
public void RemoveEmptyFolders(DataTable dt)
{
    if (recursionLevel != totalRecursionOccurred)
    {
        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            DataRow dr = dt.Rows[i];
            if (Convert.ToInt32(dr["FILECOUNT"]) == 0)
            {
                if (Convert.ToInt32(dr["DIRECTORYCOUNT"]) == 0 && Convert.ToInt32(dr["FILECOUNT"]) == 0)
                {
                    Directory.Delete(dr["PATH"].ToString());
                    dr.Delete();
                }
            }
        }

        for (int i = dt.Rows.Count - 1; i >= 0; i--)
        {
            DataRow dr = dt.Rows[i];
            dr["DIRECTORYCOUNT"] = Directory.GetDirectories(dr["PATH"].ToString()).Count();
            dr["FILECOUNT"] = Directory.GetFiles(@dr["PATH"].ToString()).Count();
        }

        if (dt.Rows.Count == 0 || (dt.Rows.Count == 1 && dt.Rows[0]["PATH"].ToString() == rootDirectory))
            return;
        else
        {
            totalRecursionOccurred++;
            RemoveEmptyFolders(dt);
        }
    }
} 

GetDirectoryXml: This method will take DirectoryInfo as an argument and return the XML as below format.

<DIRECTORY NAME="Test" PATH="C:\Users\mohitp\Desktop\Test" DIRECTORYCOUNT="2" FILECOUNT="1">
<pre>  <FILE NAME="Text1.txt" PATH="C:\Users\mohitp\Desktop\Test\Text1.txt" />
  <DIRECTORY NAME="1" PATH="C:\Users\mohitp\Desktop\Test\1" DIRECTORYCOUNT="3" FILECOUNT="0">
    <DIRECTORY NAME="I" PATH="C:\Users\mohitp\Desktop\Test\1\I" DIRECTORYCOUNT="0" FILECOUNT="0" />
    <DIRECTORY NAME="II" PATH="C:\Users\mohitp\Desktop\Test\1\II" DIRECTORYCOUNT="2" FILECOUNT="0">
      <DIRECTORY NAME="VI" PATH="C:\Users\mohitp\Desktop\Test\1\II\VI" DIRECTORYCOUNT="0" FILECOUNT="0" />
      <DIRECTORY NAME="VII" PATH="C:\Users\mohitp\Desktop\Test\1\II\VII" DIRECTORYCOUNT="0" FILECOUNT="1">
        <FILE NAME="x.txt" PATH="C:\Users\mohitp\Desktop\Test\1\II\VII\x.txt" />
      </DIRECTORY>
    </DIRECTORY>
    <DIRECTORY NAME="III" PATH="C:\Users\mohitp\Desktop\Test\1\III" DIRECTORYCOUNT="0" FILECOUNT="0" />
  </DIRECTORY>
  <DIRECTORY NAME="2" PATH="C:\Users\mohitp\Desktop\Test\2" DIRECTORYCOUNT="2" FILECOUNT="0">
    <DIRECTORY NAME="a" PATH="C:\Users\mohitp\Desktop\Test\2\a" DIRECTORYCOUNT="2" FILECOUNT="0">
      <DIRECTORY NAME="s" PATH="C:\Users\mohitp\Desktop\Test\2\a\s" DIRECTORYCOUNT="0" FILECOUNT="0" />
      <DIRECTORY NAME="t" PATH="C:\Users\mohitp\Desktop\Test\2\a\t" DIRECTORYCOUNT="0" FILECOUNT="0" />
    </DIRECTORY>
    <DIRECTORY NAME="b" PATH="C:\Users\mohitp\Desktop\Test\2\b" DIRECTORYCOUNT="2" FILECOUNT="1">
      <FILE NAME="Text1.txt" PATH="C:\Users\mohitp\Desktop\Test\2\b\Text1.txt" />
      <DIRECTORY NAME="x" PATH="C:\Users\mohitp\Desktop\Test\2\b\x" DIRECTORYCOUNT="0" FILECOUNT="0" />
      <DIRECTORY NAME="y" PATH="C:\Users\mohitp\Desktop\Test\2\b\y" DIRECTORYCOUNT="0" FILECOUNT="0" />
    </DIRECTORY>
  </DIRECTORY> 
</DIRECTORY> 

"DIRECTORY" element have following attributes:
"Name" = Name of the Directory
"Path" = Physical path of the Directory
"DIRECTORYCOUNT" = Total number of directory exists in that path
"FILECOUNT" = Total number of files exists in that path

"FILE" element have following attributes:
"Name" = Name of the File
"Path" = Physical path of the File

ConvertXMLToDataSet: Whichever XML is generated in "GetDirectoryXml" method is passed to this method. This method will convert XML string into the DataSet. And from the resultant DataSet, "DIRECTORY" table will pass to "RemoveEmptyFolders" method.

RemoveEmptyFolders: This method will perform the recursion on the DataTable for DIRECTORY list and remove the Empty folders. This method perform only those number of recursions that is selected by user on the screen. After performing that number of recursions the application will stop deleting folders.

In this method first for loop will delete the blank directories. The second for loop will again count the total number of directories and files for the remain entries into the DataTable. Because it might be possible that Directory Count and File Count may be affected after deletion of directories in first for loop. After re-calculation the total File and Directory counts there is recursion will occur.

History

  • 29 Mar 2013 - First version. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mohit_Patel

India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 4 PinmemberMohit_Patel1-Apr-13 1:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 29 Mar 2013
Article Copyright 2013 by Mohit_Patel
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid