Purushottam Rathore

Purushottam Rathore

  • 94
  • 19.2k
  • 8.7m

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

        }

    }

}