You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#删除C盘所有子目录中含指定字符串的文件?

代码问题排查与修复方案

原代码存在的问题

  • 方法调用错误:System.IO.SearchOption.AllDirectories是枚举值,不能直接作为方法调用。获取文件列表需要用Directory.GetFiles方法,传入路径、搜索模式和搜索选项。
  • 权限隐患:C盘根目录下的系统文件夹(如Windows、Program Files)需要管理员权限才能操作,直接运行代码会触发权限异常。
  • 无异常处理:删除文件时可能遇到文件被占用、权限不足、文件已被删除等情况,未处理这些异常会导致程序直接崩溃。
  • 日志格式错误:file + "will be deleted"缺少空格,会输出类似C:\testapple.algowill be deleted的混乱日志。

修复后的完整代码

void DeleteFilesContainingApple()
{
    string rootFolderPath = @"C:\";
    string searchPattern = @"*apple*.algo"; // 匹配文件名含apple、后缀为algo的文件

    try
    {
        // 递归遍历所有子目录,获取目标文件列表
        string[] fileList = System.IO.Directory.GetFiles(
            rootFolderPath,
            searchPattern,
            System.IO.SearchOption.AllDirectories
        );

        foreach (string file in fileList)
        {
            System.Diagnostics.Debug.WriteLine($"{file} will be deleted");
            try
            {
                System.IO.File.Delete(file);
            }
            catch (System.IO.IOException ex)
            {
                System.Diagnostics.Debug.WriteLine($"删除失败 {file}: {ex.Message}");
            }
            catch (System.UnauthorizedAccessException ex)
            {
                System.Diagnostics.Debug.WriteLine($"权限不足无法删除 {file}: {ex.Message}");
            }
        }
    }
    catch (System.UnauthorizedAccessException ex)
    {
        System.Diagnostics.Debug.WriteLine($"访问C盘根目录权限不足: {ex.Message}");
    }
    catch (System.IO.DirectoryNotFoundException ex)
    {
        System.Diagnostics.Debug.WriteLine($"目录不存在: {ex.Message}");
    }
}

关键注意事项

  • 运行权限:必须以管理员身份启动程序,否则无法访问C盘的受保护系统文件夹。
  • 预校验建议:正式删除前,先注释掉File.Delete代码,只输出文件路径,确认目标文件符合预期,避免误删重要数据。
  • 性能优化:遍历整个C盘耗时较长,若不需要全局搜索,可缩小rootFolderPath到指定子目录。

内容的提问来源于stack exchange,提问作者tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:32:08