Purushottam Rathore

Purushottam Rathore

  • 216
  • 8.7k
  • 8.8m

How to delete all empty folders in directory?

Apr 18 2013 6:19 AM

With the help of this code you can delete all empty folders (you can say sub directory) in a directory using C#.

//This method is used for delete all subdirectory if they are empty.

private void DeleteDirectory()

{

    string path ="~/UploadFiles/CastingImages/";
    if (Directory.Exists(Server.MapPath(path)))

    {

        //Delete all child Directories if they are empty

        foreach (string subdirectory in Directory.GetDirectories(Server.MapPath(path)))

        {

            string[] file = Directory.GetFiles(subdirectory, "*.*");

            if (file.Length == 0)

                Directory.Delete(subdirectory);

        }

    }

}