搜索所有子目录中的某些文件,跳过某些文件夹[英] searching all subdirectories for certain files, skipping some folders

本文是小编为大家收集整理的关于搜索所有子目录中的某些文件,跳过某些文件夹的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我想获取具有特定扩展名但跳过特定文件夹的所有文件的所有路径.我使用的代码可以正常工作,但不排除指定的文件夹.

public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
    try
    {
        var dirFiles = Enumerable.Empty<string>();
        if (searchOpt == SearchOption.AllDirectories)
        {
            dirFiles = Directory.EnumerateDirectories(path)
                .Where(y => !y.Contains("Program Files") || !y.Contains("Windows"))
                .SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
        }
        return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
    }
    catch (UnauthorizedAccessException ex)
    {
        return Enumerable.Empty<string>();
    }
}

但根据我对其他问题的研究,这正是我应该做的.请问我哪里错了?

用法如下:

var enumerable = EnumerateFiles(@"C:\", "*.jpg", SearchOption.AllDirectories);

推荐答案

我猜你想排除Program Files 和 Windows,所以使用&&而不是||.

.Where(y => !y.Contains("Program Files") && !y.Contains("Windows"))

本文地址:https://www.itbaoku.cn/post/1556829.html

问题描述

I want to get all paths to all files with a certain extension but skipping certain folders. I use this code which works fine but does not exclude the specified folders.

public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
    try
    {
        var dirFiles = Enumerable.Empty<string>();
        if (searchOpt == SearchOption.AllDirectories)
        {
            dirFiles = Directory.EnumerateDirectories(path)
                .Where(y => !y.Contains("Program Files") || !y.Contains("Windows"))
                .SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
        }
        return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
    }
    catch (UnauthorizedAccessException ex)
    {
        return Enumerable.Empty<string>();
    }
}

But based on my research of other questions this is exactly what I should be doing. Where am I going wrong please?

Usage would be:

var enumerable = EnumerateFiles(@"C:\", "*.jpg", SearchOption.AllDirectories);

推荐答案

I guess that you want to exlude Program Files and Windows, so use && instead of ||.

.Where(y => !y.Contains("Program Files") && !y.Contains("Windows"))