首页 > 解决方案 > 从数组中检查目录的名称

问题描述

我正在开发一个程序,该程序应该扫描特定目录以查找其中具有特定名称的任何目录,如果找到它们,请告诉用户。

目前,我加载其搜索的名称的方式是这样的:

static string path = Path.Combine(Directory.GetCurrentDirectory(), @"database.txt");
static string[] database = File.ReadAllLines(datapath);

在查看特定目录时,我将其用作要查找的名称数组。我正在使用 foreach 方法这样做。

System.IO.DirectoryInfo di = new DirectoryInfo("C:\ExampleDirectory");
        foreach (DirectoryInfo dir in di.GetDirectories())
        {

        }

有没有办法查看文件“database.txt”中的任何名称是否与“C:\ExampleDirectory”中找到的任何目录名称匹配?

我能想到的唯一方法是:

System.IO.DirectoryInfo di = new DirectoryInfo(versionspath);
        foreach (DirectoryInfo dir in di.GetDirectories())
        {
            if(dir.Name == //Something...) {
            Console.WriteLine("Match found!");
            break;}
        }

但这显然行不通,我想不出任何其他方法来做到这一点。任何帮助将不胜感激!

标签: c#arraysdirectorymatch

解决方案


像往常一样,LINQ 是要走的路。每当您必须在两个列表之间以及两个包含不同类型的列表之间查找匹配或不匹配时,您都必须使用.Join()or .GroupJoin()

如果.Join()您需要找到 1:1 关系以及.GroupJoin()任何类型的 1-to 关系(1:0、1:many 或 1:1),则 开始发挥作用。

因此,如果您需要与您的列表匹配的目录,这听起来对.Join()操作员来说是一项工作:

public static void Main(string[] args)
{
    // Where ever this comes normally from.
    string[] database = new[] { "fOo", "bAr" };
    string startDirectory = @"D:\baseFolder";

    // A method that returns an IEnumerable<string>
    // Using maybe a recursive approach to get all directories and/or files
    var candidates = LoadCandidates(startDirectory);

    var matches = database.Join(
        candidates,
        // Simply pick the database entry as is.
        dbEntry => dbEntry,
        // Only take the last portion of the given path.
        fullPath => Path.GetFileName(fullPath),
        // Return only the full path from the given matching pair.
        (dbEntry, fullPath) => fullPath,
        // Ignore case on comparison.
        StringComparer.OrdinalIgnoreCase);

    foreach (var match in matches)
    {
        // Shows "D:\baseFolder\foo"
        Console.WriteLine(match);
    }

    Console.ReadKey();
}

private static IEnumerable<string> LoadCandidates(string baseFolder)
{
    return new[] { @"D:\baseFolder\foo", @"D:\basefolder\baz" };
    //return Directory.EnumerateDirectories(baseFolder, "*", SearchOption.AllDirectories);
}

推荐阅读