gpt4 book ai didi

c# - 有没有办法使用搜索选项 : All directories but it skips to the next folder after searching first layer of the folder

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:19 25 4
gpt4 key购买 nike

我有一个很大的文件夹,里面有多个子目录,我想找的文件只在那些子目录的第一层,我试过了SearchOption.AllDirectories 但它需要太多时间。有没有办法让函数不搜索整个子目录,而只搜索它的第一层

我已经尝试使用 Directory.EnumerateFiles 但它仍然占用太多时间

foreach (string file in Directory.EnumerateFiles(
@"\\Computer1\",
"Application.exe",
SearchOption.AllDirectories)) {
...
}

最佳答案

您可以尝试嵌套查询:

  1. 枚举 顶级目录 @"\\Computer1\"
  2. 枚举这些顶级目录中的文件:

代码:

using System.IO;
using System.Linq;

...

var files = Directory
.EnumerateDirectories( @"\\Computer1\", "*", SearchOption.TopDirectoryOnly)
.SelectMany(dir => Directory
.EnumerateFiles(dir, "Application.exe", SearchOption.TopDirectoryOnly));

foreach (var file in files) {
...
}

编辑:如果要枚举第 1 级和第 2 级的文件,可以再次嵌套查询:

var files = Directory
.EnumerateDirectories( @"\\Computer1\", "*", SearchOption.TopDirectoryOnly)
.SelectMany(dir => Directory
// 1st level
.EnumerateFiles(dir, "Application.exe", SearchOption.TopDirectoryOnly)
// 2nd level
.Concat(Directory
.EnumerateDirectories(dir, "*", SearchOption.TopDirectoryOnly)
.SelectMany(subdir => Directory.EnumerateFiles(subdir, "Application.exe", SearchOption.TopDirectoryOnly))));

一般情况下我们可以实现

private static IEnumerable<string> EnumerateDirectories(string root, int level) {
int current = 0;

Queue<string> agenda = new Queue<string>();

agenda.Enqueue(root);

while (current <= level) {
var list = agenda.ToList();

agenda.Clear();

foreach (var dir in list) {
if (current > 0)
yield return dir;

if (current < level)
foreach (var subdir in Directory.EnumerateDirectories(dir))
agenda.Enqueue(subdir);
}

current += 1;
}
}

使用它:

// All subdirectories, up and including 2nd level
var files = EnumerateDirectories(@"\\Computer1\", 2)
.SelectMany(dir => Directory
.EnumerateFiles(dir, "Application.exe", SearchOption.TopDirectoryOnly));

foreach (var file in files) {
...
}

关于c# - 有没有办法使用搜索选项 : All directories but it skips to the next folder after searching first layer of the folder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58389780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com