参照1:
public static string[] GetDirectories2(string dir, string regexPattern = null, int depth = 0, bool throwEx = false) { List<string> lst = new List<string>(); try { foreach (string item in Directory.GetDirectories(dir)) { try { if (regexPattern != null && item.Contains(regexPattern)) { lst.Add(item); } //递归 if (depth != 0) { lst.AddRange(GetDirectories2(item, regexPattern, depth - 1, throwEx)); } } catch { if (throwEx) { throw; } } } } catch { if (throwEx) { throw; } } return lst.ToArray(); }
调用:DirUtil.GetDirectories2(rootDir, "Log_PayLogUnWrite", 6);
参照2,这个方法是遇到第一个匹配的则返回,有需要的自己修改:
/// <summary> /// 查找指定名称的文件夹,默认深度6 /// </summary> /// <param name="path">要查找的路径</param> /// <param name="searchDirName">要查找的文件夹名称</param> /// <param name="depth">查找深度</param> /// <returns></returns> List<string> FindDirPath(string path, string searchDirName, int depth = 6) { List<string> lst = new List<string>(); try { string[] dirs = Directory.GetDirectories(path); foreach (string dir in dirs) { if (dir.Contains("$RECYCLE.BIN") || dir.Contains("System Volume Information")) continue; string dirName = dir.Substring(dir.LastIndexOf("\\") + 1); if (dirName.ToLower().EndsWith("temp")) //本程序需要跳过temp文件夹 continue; if (dirName == searchDirName) { lst.Add(dir); break; //遇到第一个匹配则返回 } //递归 if (depth != 0) { lst.AddRange(FindDirPath(dir, searchDirName)); } } } catch (Exception ex) { UILog("FindDirPath1 ex:" + ex.Message); } return lst; }
调用 :List<string> lst = FindDirPath("d:\\", Folder);
原文:https://www.cnblogs.com/runliuv/p/11416244.html