C#递归查找符合条件的文件或文件夹

文章描述了使用递归方法在给定路径下查找具有特定后缀类型的文件,并且检查文件夹是否包含名为AAA和BBB的子文件夹,将符合条件的文件路径和文件夹路径存储在并发队列中。
摘要由CSDN通过智能技术生成

递归查找符合条件的文件,条件为后缀类型,并将结果存贮到队列中

 public void TraverseFiles(string folderPath, string type, ConcurrentQueue<string> folderPathsQueue)
 {
     try
     {
         // 遍历当前文件夹下的所有文件符合条件的文件
         foreach (string filePath in Directory.GetFiles(folderPath))
         {
             string[] tempArray = filePath.Split('.');
             if (tempArray[tempArray.Length - 1] == type)
             {
                 folderPathsQueue.Enqueue(filePath);
             }
         }

         // 遍历文件夹下的所有子文件夹
         foreach (string subFolderPath in Directory.GetDirectories(folderPath))
         {
             // 递归调用遍历文件夹方法
             TraverseFiles(subFolderPath, type, folderPathsQueue);
         }
     }
     catch (UnauthorizedAccessException)
     {
         // 如果无法访问文件夹,则在此处处理异常
     }
 }

递归查找符合条件的文件夹,这里判断的是文件夹下包含名字为AAA和BBB的文件夹并存入foldersPath队列

ConcurrentQueue<string> foldersPath = new ConcurrentQueue<string>();//文件夹路径队列
public void TraverseFolders(string folderPath)
{
    // 判断文件夹是否存在
    if (!Directory.Exists(folderPath))
    {
        return;
    }

    // 判断文件夹是否同时包含名称为"AAA"和"BBB"的两个文件夹
    if (Directory.Exists(Path.Combine(folderPath, "AAA")) && Directory.Exists(Path.Combine(folderPath, "BBB")))
    {
        foldersPath.Enqueue(folderPath);
    }

    // 遍历子文件夹
    string[] subFolders = Directory.GetDirectories(folderPath);
    foreach (string subFolder in subFolders)
    {
        TraverseFolders(subFolder);
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值