Friday, April 15, 2011

C# Traverse Directory Tree Recursive - Delete empty directories

using System.IO;

using System.Linq;

namespace DeleteEmptyDirs

{

  internal class Program

  {

    private static void Main(string[] args)

    {

      WalkDirectoryTree(new DirectoryInfo(args[0]));

    }

    private static void WalkDirectoryTree(DirectoryInfo root)

    {

      DirectoryInfo[] subDirs = null;

      if (IsDirectoryEmpty(root.FullName))

        root.Delete();

      else

        subDirs = root.GetDirectories();

      if (subDirs == null)

        return;

      foreach (var dirInfo in subDirs)

        WalkDirectoryTree(dirInfo);

    }

    public static bool IsDirectoryEmpty(string path)

    {

      return !Directory.EnumerateFileSystemEntries(path).Any();

    }

  }

}

Posted via email from Mocha Brain Freeze

No comments: