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

如何检查文件夹内是否存在任意文件?替代指定文件的File.Exists用法

检查指定文件夹是否存在任意文件的方法

你可以用Directory.EnumerateFiles()结合LINQ的Any()方法来实现,这个方式比一次性获取所有文件列表更高效——它会在找到第一个文件时就停止遍历,不用加载全部文件到内存里。

核心实现代码

public bool HasAnyFiles(string folderPath)
{
    // 先确认目标文件夹存在
    if (!Directory.Exists(folderPath))
        return false;
    
    // 枚举文件夹内的所有文件,只要存在至少一个就返回true
    return Directory.EnumerateFiles(folderPath).Any();
}

适配你的循环检查场景

如果要循环等待文件夹清空,可以加入延迟检查避免资源浪费:

string targetFolder = @"C:\Users\gcaor\Desktop\OC";
while (HasAnyFiles(targetFolder))
{
    // 每隔1秒检查一次,可根据需求调整间隔
    await Task.Delay(1000);
}

// 到这里说明文件夹已无文件,执行后续流程

额外补充

  • 如果需要包含子文件夹内的文件,修改枚举参数即可:
    return Directory.EnumerateFiles(folderPath, "*", SearchOption.AllDirectories).Any();
    
  • 可以添加异常处理,应对权限不足、文件夹被占用等情况:
    public bool HasAnyFiles(string folderPath)
    {
        try
        {
            if (!Directory.Exists(folderPath))
                return false;
            
            return Directory.EnumerateFiles(folderPath).Any();
        }
        catch (UnauthorizedAccessException)
        {
            // 无权限访问时的处理,示例返回false,也可按需抛出异常
            return false;
        }
        catch (IOException)
        {
            // IO异常(如文件夹被占用)的处理
            return false;
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:25:38