[英]Match string (most characters) using C#
我有一個文件夾結構(-有時代表一個文件夾,在其中縮進的文件夾內的文件夾)
我給了一個字符串值“ D130202”以匹配正確的文件夾,我正在使用C#的System.IO.Directory.GetDirectories(@"c:\\", "", SearchOption.TopDirectoryOnly);
我不知道要在搜索模式的空字符串中放入什么。 在此之前,我一直使用SearchOption.AllDirectories
搜索所有文件夾,直到匹配“ D130202”為止,但是由於有成千上萬個文件夾,因此要花很長時間瀏覽所有其他文件夾中的每個文件夾。
我想在該值匹配后立即從D搜索,程序進入另一個文件夾,找到D13,匹配該值,進入D1302文件夾,依此類推,而無需不必要地搜索所有其他文件夾。
但是我不知道該怎么做。
任何幫助將非常感激。
您必須遞歸搜索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);
}
用法:
SearchNestedDirectory(@"c:\", "D130202");
返回:路徑;如果找不到路徑,則返回null
。
編輯:修復了子文件夾長度增加超過1時發生的問題
將D130202的路徑構建為(以C:\\為根): C:\\ D \\ D13 \\ D1302 \\ D130202
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.