从 DirectoryInfo 中搜索父目录

有没有办法搜索特定的父目录?

我知道我可以使用这个获取目录的父级

Directory.GetParent(Directory.GetCurrentDirectory()).FullName

但这会返回直接父级,有什么方法可以在路径的目录层次结构中搜索特定的父级?

编辑

我想要实现的是,如果我有这样的当前目录

C:/Project/Source/Dev/Database

所以我想访问Source 我知道我可以通过GetParent两次调用方法来访问它的目录,但我认为这不是正确的方法,因为如果将来我的文件当前目录发生变化并且它会进一步下降怎么办。Source所以我想要一些完整的证明方式,无论我在当前目录中有多深,我都可以直接找到目录的路径,因为那肯定我会在目录中Source

所以像

FindParent('Source')


慕桂英3389331
浏览 177回答 4
4回答

梵蒂冈之花

您可以尝试这样的事情(for循环):private static IEnumerable<String> ParentDirectories(string directory = null) {&nbsp; for (string dir = null == directory ? Directory.GetCurrentDirectory() : directory;&nbsp; &nbsp; &nbsp; &nbsp;dir != null;&nbsp; &nbsp; &nbsp; &nbsp;dir = Directory.GetParent(dir)?.FullName)&nbsp; &nbsp; yield return dir;}演示:var demo = string.Join(Environment.NewLine,&nbsp;&nbsp; ParentDirectories(@"C:/Project/Source/Dev/Database"));Console.Write(demo);结果:C:/Project/Source/Dev/Database // initial directoryC:\Project\Source\Dev&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // and its all parentsC:\Project\SourceC:\ProjectC:\如果您不想包含目录本身,请添加.Skip(1):var demo = string.Join(Environment.NewLine,&nbsp;&nbsp; ParentDirectories(@"C:/Project/Source/Dev/Database").Skip(1));最后,如果你想找到一个以 结尾的父目录Source:string dirName = "Source";string myParent = ParentDirectories(@"C:/Project/Source/Dev/Database")&nbsp; .FirstOrDefault(dir => string.Equals(&nbsp; &nbsp; &nbsp;dirName,&nbsp; &nbsp; &nbsp;new DirectoryInfo(dir).Name,&nbsp;&nbsp; &nbsp; &nbsp;StringComparison.OrdinalIgnoreCase));Console.Write(myParent);&nbsp;结果:C:\Project\Source

梦里花落0921

Directory.GetCurrentDirectory()返回一个字符串,表示当前目录的完整绝对路径。如果要获取特定父目录的路径,可以简单地使用substring:var path = Directory.GetCurrentDirectory(); // Suppose C:/Project/Source/Dev/Databasevar sourceDir = new string[] {Path.DirectorySeparatorChar + "Source" + Path.DirectorySeparatorChar,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Path.AltDirectorySeparatorChar + "Source" + Path.AltDirectorySeparatorChar};var sourcePath = path.IndexOf(sourceDir[0], StringComparison.OrdinalIgnoreCase) > -1 ?&nbsp; &nbsp; path.Substring(0, path.IndexOf(sourceDir[0]) + sourceDir[0].Length) :&nbsp; &nbsp; path.IndexOf(sourceDir[1], StringComparison.OrdinalIgnoreCase) > -1 ?&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; path.Substring(0, path.IndexOf(sourceDir[1]) + sourceDir[1].Length) :&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; null;我使用Path.DirectorySeparatorCharandPath.AltDirectorySeparatorChar作为分隔符,以便代码在每个平台上都可以正常工作。

慕沐林林

在遍历任何类型的序列(数字序列、目录序列、图中的节点序列)时,您可以选择使用递归。目录结构(当忽略任何类型的链接时)是称为有向无环图(或 DAG)的数据结构的子集——这个子集通常不会重新加入并且永远扇出(只要操作系统允许给定嵌套目录的深度)。我们通常将其称为树结构。从这个角度来看,递归表面的概念对大多数人来说可能并不奇怪,因为程序员应用递归来遍历树是很常见的。但是,无论您是向上还是向下遍历树只是一个实现细节。没有理由不能使用递归来遍历树。这是一个简单的控制台应用程序(使用 .net6 约定和 C#10 语法编写),您可以学习它,然后也许可以应用它来解决未来的问题。using System.Runtime.InteropServices; // For the [Optional] attributevar dir = Directory.GetCurrentDirectory();var file = Directory.GetFiles(dir).First();var projFile = DirectoryRecursor.RecurseUpwardsUntilFileIsFoundWith(".csproj", file, 5);Console.WriteLine(projFile);public static class DirectoryRecursor{&nbsp; &nbsp; public static FileInfo? RecurseUpwardsUntilFileIsFoundWith(&nbsp; &nbsp; &nbsp; &nbsp; string stringToMatch,&nbsp; &nbsp; &nbsp; &nbsp; string sourceFile,&nbsp; &nbsp; &nbsp; &nbsp; [Optional] int? maxParentDirLevel)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (maxParentDirLevel is not null && maxParentDirLevel == 0) return null; // try and stave off disaster&nbsp; &nbsp; &nbsp; &nbsp; var dirName = Path.GetDirectoryName(sourceFile);&nbsp; &nbsp; &nbsp; &nbsp; if (dirName is null) return null;&nbsp; &nbsp; &nbsp; &nbsp; var csprojFile = Directory.GetFiles(dirName).Where(x => x.EndsWith(stringToMatch)).SingleOrDefault();&nbsp; &nbsp; &nbsp; &nbsp; if (csprojFile is null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (ThereIsAParentDirectory(new DirectoryInfo(sourceFile), out var parentDir))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return RecurseUpwardsUntilFileIsFoundWith(stringToMatch, parentDir.FullName, maxParentDirLevel - 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new FileInfo(csprojFile);&nbsp; &nbsp; }&nbsp; &nbsp; public static bool ThereIsAParentDirectory(DirectoryInfo dir, out DirectoryInfo parentDir)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (dir.Parent is not null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parentDir = dir.Parent;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return dir.Parent.Exists;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; parentDir = dir;&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}一个快速的旁注:在树上和下应用递归的一个例子(我承认它目前不是开源的),是www.palavyr.com上的对话构建器。这个对话树被实现为一个双链表,以促进对话树上下的递归。我正计划制作一篇技术博客文章来解释这个实现——一旦我完成了它,我会用它来更新这个响应。

HUX布斯

实际上,我认为已经存在一种方式或功能,但是如果我必须自己编写,那么我编写的这个解决方案对我有用&nbsp; &nbsp; private static string GetParent(string directoryPath, string parent)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DirectoryInfo directory = new DirectoryInfo(directoryPath);&nbsp; &nbsp; &nbsp; &nbsp; while (directory.Parent!=null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (directory.Parent.Name.ToLower() == parent.ToLower())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return directory.Parent.FullName;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; directory = directory.Parent;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP