C# 搜索子目录(不搜索文件)

发布于 2024-08-27 18:26:19 字数 124 浏览 4 评论 0原文

我看到的每个示例似乎都是仅使用文件递归获取子目录中的文件。我想做的是在文件夹中搜索名为“xxx”的特定子目录,然后将该路径保存到变量中,以便我可以将其用于其他用途。

这是否可以在不循环所有目录并按名称比较的情况下实现?

Every example I see seems to be for recursively getting files in subdirectories uses files only. What I'm trying to do is search a folder for a particular subdirectory named "xxx" then save that path to a variable so I can use it for other things.

Is this possible without looping through all the directories and comparing by name?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

还不是爱你 2024-09-03 18:26:19

我们

Directory.GetDirectories(root);

将返回一个子目录数组。

然后,您可以使用 Linq 来查找您感兴趣的循环:

IEnumerable<string> list = Directory.GetDirectories(root).Where(s => s.Equals("test"));

它不是代码中的循环,但仍然是循环。所以最终的答案是“不,如果不循环,你就找不到文件夹‘test’”。

您可以将 .SingleOrDefault() 添加到 Linq,但这取决于您在找不到“test”文件夹时想要执行的操作。

如果您更改 GetDirectories 调用以包含 SearchOption SearchOption.AllDirectories 那么它也会为您执行递归。此版本支持搜索 - 您必须提供搜索字符串 - 尽管在 .NET Framework 中它是区分大小写的搜索。要返回所有子目录,请传递 "*" 作为搜索词。

显然,在这种情况下,如果目录树中存在多个名为“test”的文件夹,则调用可能会返回多个项目。

Well

Directory.GetDirectories(root);

will return you an array of the subdirectories.

You can then use Linq to find the one you're interested in:

IEnumerable<string> list = Directory.GetDirectories(root).Where(s => s.Equals("test"));

which isn't a loop in your code, but is still a loop nevertheless. So the ultimate answer is that "no you can't find a folder 'test' without looping".

You could add .SingleOrDefault() to the Linq, but that would depend on what you wanted to do if your "test" folder couldn't be found.

If you change the GetDirectories call to include the SearchOption SearchOption.AllDirectories then it will do the recursion for you as well. This version supports searching - you have to supply a search string - though in .NET Framework it's case sensitive searching. To return all sub directories you pass "*" as the search term.

Obviously in this case the call could return more than one item if there was more than one folder named "test" in your directory tree.

樱桃奶球 2024-09-03 18:26:19
var foldersFound = Directory.GetDirectories(root, "test", SearchOption.AllDirectories)

这将返回一个字符串数组,其中包含找到的给定名称的所有文件夹。您可以更改最后一个参数,以便它只检查顶级目录,并且您可以更改 root 来调整它的起始位置。

var foldersFound = Directory.GetDirectories(root, "test", SearchOption.AllDirectories)

This will return a string array with all the folders found with the given name. You can change the last parameter so that it only checks top level directories and you can change root to adjust where it is starting from.

把回忆走一遍 2024-09-03 18:26:19

首先,“不,如果不循环遍历所有目录并按名称进行比较,这是不可能的”。

我相信您真正的问题是“是否有一个现有的 API 可以处理所有目录的循环并按名称进行比较?”

是的,有。它称为Directory.Exists()

var xxxPath = Path.Combine(parentFolder, "xxx");
if (Directory.Exists(xxxPath))
    savedPath = xxxPath;

First of all, "No, it is not possible without looping through all the directories and comparing by name".

I believe your real question is "Is there an existing API which will handle looping through all the directories and comparing by name for me?"

Yes, there is. It's called Directory.Exists():

var xxxPath = Path.Combine(parentFolder, "xxx");
if (Directory.Exists(xxxPath))
    savedPath = xxxPath;
澜川若宁 2024-09-03 18:26:19

是的,我相信唯一可用的解决方案(缺少第三方库)是通过名称比较递归搜索目录。

Yes, I believe that the only available solution (short of third party libraries) is a recursive search for the directory via name comparison.

夏末的微笑 2024-09-03 18:26:19

您也可以使用 Windows Search,它也为 .Net 提供 api。以下是更详细的信息:面向开发人员的 Windows Search 4.0< /a>

You can use Windows Search which provides api for .Net too. Here is more detailed information: Windows Search 4.0 for Developers

酒儿 2024-09-03 18:26:19

以下是在考虑 UnauthorizedAccessException 的同时使用两个过滤器搜索文件夹的代码片段,可以将其重构为仅使用一个过滤器:

public static string FindGitPath(string firstFilter, string secondFilter, string initialPath)
    {
        string gitPath = string.Empty;
        foreach (var i in Directory.GetDirectories(initialPath)) {          
            try {
                foreach (var f in Directory.GetDirectories(i, firstFilter, SearchOption.AllDirectories)) {
                    foreach (var s in Directory.GetDirectories(f)) {
                        if (s == Path.Combine(f,secondFilter)) {
                            gitPath = f;
                            break;
                        }
                    }
                }       
            } catch (UnauthorizedAccessException) {
                Console.WriteLine("Path is not accessible: {0}", i);
            }                               
        }
        return gitPath; 
    }

用法示例:

Console.WriteLine("Retrieved the git database folder as {0}", FindGitPath("database",".git", "c:\\"));

Here is a snippet for searching for a folder using two filters while considering for the UnauthorizedAccessException, it can be refactored to use only one filter:

public static string FindGitPath(string firstFilter, string secondFilter, string initialPath)
    {
        string gitPath = string.Empty;
        foreach (var i in Directory.GetDirectories(initialPath)) {          
            try {
                foreach (var f in Directory.GetDirectories(i, firstFilter, SearchOption.AllDirectories)) {
                    foreach (var s in Directory.GetDirectories(f)) {
                        if (s == Path.Combine(f,secondFilter)) {
                            gitPath = f;
                            break;
                        }
                    }
                }       
            } catch (UnauthorizedAccessException) {
                Console.WriteLine("Path is not accessible: {0}", i);
            }                               
        }
        return gitPath; 
    }

Usage example:

Console.WriteLine("Retrieved the git database folder as {0}", FindGitPath("database",".git", "c:\\"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文