C# 遍历删除空文件夹

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("用法: xxx.exe <目录路径>");
            Console.WriteLine("示例: xxx.exe C:\\MyFolder");
            Console.ReadKey();
            return;
        }

        string rootPath = args[0];

        if (!Directory.Exists(rootPath))
        {
            Console.WriteLine($"路径不存在: {rootPath}");
            Console.ReadKey();
            return;
        }

        DeleteEmptyDirectories(rootPath);
    }

    static void DeleteEmptyDirectories(string rootPath)
    {
        // 1. 获取所有子目录(递归)
        var allDirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories);

        // 2. 按路径长度降序排列(深度优先:从最深层开始)
        var sortedDirs = allDirs.OrderByDescending(d => d.Length).ToList();

        int deletedCount = 0;

        // 3. 遍历删除空目录
        foreach (var dir in sortedDirs)
        {
            if (IsDirectoryEmpty(dir))
            {
                try
                {
                    Directory.Delete(dir);
                    Console.WriteLine($"删除空目录: {dir}");
                    deletedCount++;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"删除失败: {dir},原因: {ex.Message}");
                }
            }
        }

        // 4. 检查并删除根目录
        if (IsDirectoryEmpty(rootPath))
        {
            try
            {
                Directory.Delete(rootPath);
                Console.WriteLine($"删除空根目录: {rootPath}");
                deletedCount++;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除根目录失败: {rootPath},原因: {ex.Message}");
            }
        }

        Console.WriteLine($"共删除 {deletedCount} 个空文件夹");
    }

    static bool IsDirectoryEmpty(string dirPath)
    {
        // 如果目录不存在,返回 true
        if (!Directory.Exists(dirPath)) return true;

        // 检查是否包含任何文件或子目录
        return !Directory.EnumerateFileSystemEntries(dirPath).Any();
    }
}
posted @ 2026-08-13 11:37  double64  阅读(5)  评论(0)    收藏  举报