c# - 从数组中检查目录的名称
问题描述
我正在开发一个程序,该程序应该扫描特定目录以查找其中具有特定名称的任何目录,如果找到它们,请告诉用户。
目前,我加载其搜索的名称的方式是这样的:
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;}
}
但这显然行不通,我想不出任何其他方法来做到这一点。任何帮助将不胜感激!
解决方案
像往常一样,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);
}
推荐阅读
- mongodb - MongoDB atlas 错误:uncaughtException:(未授权)管理员未授权执行命令
- javascript - Phaser 3:更改场景的大小而不影响其下方的较大场景
- java - 尝试调用虚拟方法 'void android.widget.GridView.setAdapter(android.widget.ListAdapter
- android - 如何从画廊添加视频并在 android studio 的 videoview 上播放?
- google-sheets - GoogleSheet 求和直到空行并按“个人”分组
- dokku - 部署在 dokku-ubuntu-s-1vcpu-1gb-nyc1-01 上时如何访问 Dokku 上的应用程序?
- amazon-web-services - DynamoDB flush latency
- excel - 将工作表从一个工作簿复制到另一个工作簿公式不会重新计算
- c++ - 我无法理解 C++ 向量声明中的这种变量类型
- google-sheets - 如何从字符串中提取两个共享相同前言的单词?