简体   繁体   English

使用C#匹配字符串(大多数字符)

[英]Match string (most characters) using C#

I have a folder structure (the - represent a folder sometimes, folders within folders where they are indented) 我有一个文件夹结构(-有时代表一个文件夹,在其中缩进的文件夹内的文件夹)

在此处输入图片说明

I'm given a string value of "D130202" to match the correct folder, I'm using C#'s System.IO.Directory.GetDirectories(@"c:\\", "", SearchOption.TopDirectoryOnly); 我给了一个字符串值“ D130202”以匹配正确的文件夹,我正在使用C#的System.IO.Directory.GetDirectories(@"c:\\", "", SearchOption.TopDirectoryOnly);

I don't know what to put into the empty string for the search pattern. 我不知道要在搜索模式的空字符串中放入什么。 Before, I was searching through all the folders with SearchOption.AllDirectories until I matched "D130202" but it was taking a long time going through every folder within all the other folders because there are thousands of folders. 在此之前,我一直使用SearchOption.AllDirectories搜索所有文件夹,直到匹配“ D130202”为止,但是由于有成千上万个文件夹,因此要花很长时间浏览所有其他文件夹中的每个文件夹。

I would like to search from D as soon as that value is matched, the program goes into the other folder, finds D13, matches that value, goes into the D1302 folder and so on without unnecessarily searching through all the other folders. 我想在该值匹配后立即从D搜索,程序进入另一个文件夹,找到D13,匹配该值,进入D1302文件夹,依此类推,而无需不必要地搜索所有其他文件夹。

But I cannot think how I would do this. 但是我不知道该怎么做。

Any help would be much appreciated. 任何帮助将非常感激。

You have to search the TopDirectoryOnly recursively: 您必须递归搜索TopDirectoryOnly

public string SearchNestedDirectory(string path, string name)
{
    if (string.IsNullOrEmpty(name))
        throw new ArgumentException("name");

    return SearchNestedDirectoryImpl(path, name);
}
private string SearchNestedDirectoryImpl(string path, string name, int depth = 1)
{
    if (depth > name.Length)
        return null;

    var result = Directory.GetDirectories(path, name.Substring(0, depth)).FirstOrDefault();
    if (result == null)
        return SearchNestedDirectoryImpl(path, name, depth + 1);

    if (result != null && Regex.Replace(result, @".+\\", "") == name)
        return result;

    return SearchNestedDirectoryImpl(result, name, depth + 1);
}

Usage: 用法:

SearchNestedDirectory(@"c:\", "D130202");

Returns: the path, or null if the path cannot be found. 返回:路径;如果找不到路径,则返回null

EDIT: fixed an issue that occurs when subfolder length is increased by more than 1 编辑:修复了子文件夹长度增加超过1时发生的问题

I would utilize Directory.Exists(path) 我会利用Directory.Exists(path)

Build the path from D130202 as (with C:\\ as root): C:\\D\\D13\\D1302\\D130202 将D130202的路径构建为(以C:\\为根): C:\\ D \\ D13 \\ D1302 \\ D130202

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM