简体   繁体   中英

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);

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.

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.

But I cannot think how I would do this.

Any help would be much appreciated.

You have to search the TopDirectoryOnly recursively:

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.

EDIT: fixed an issue that occurs when subfolder length is increased by more than 1

I would utilize Directory.Exists(path)

Build the path from D130202 as (with C:\\ as root): C:\\D\\D13\\D1302\\D130202

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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