C#获取给定路径的文件夹深度的最佳方法?

我正在研究需要遍历文件系统的东西,对于任何给定的路径,我需要知道我在文件夹结构中的“深度”。 这是我目前正在使用的内容:

int folderDepth = 0; string tmpPath = startPath; while (Directory.GetParent(tmpPath) != null) { folderDepth++; tmpPath = Directory.GetParent(tmpPath).FullName; } return folderDepth; 

这有效,但我怀疑有更好/更快的方式? 很有必要提供任何反馈意见。

脱离我的头顶:

 Directory.GetFullPath().Split("\\").Length; 

我迟到了,但我想指出Paul Sonier的回答可能是最短的,但应该是:

  Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length; 

我一直是递归解决方案的粉丝。 效率低下,但很有趣!

 public static int FolderDepth(string path) { if (string.IsNullOrEmpty(path)) return 0; DirectoryInfo parent = Directory.GetParent(path); if (parent == null) return 1; return FolderDepth(parent.FullName) + 1; } 

我喜欢用C#编写的Lisp代码!

这是另一个我更喜欢的递归版本,可能效率更高:

 public static int FolderDepth(string path) { if (string.IsNullOrEmpty(path)) return 0; return FolderDepth(new DirectoryInfo(path)); } public static int FolderDepth(DirectoryInfo directory) { if (directory == null) return 0; return FolderDepth(directory.Parent) + 1; } 

美好时光,美好时光……

假设您的路径已经过有效审查,在.NET 3.5中您也可以使用LINQ在一行代码中执行此操作…

Console.WriteLine(@“C:\ Folder1 \ Folder2 \ Folder3 \ Folder4 \ MyFile.txt”.Where(c => c = @“\”)。Count);

如果使用Path类的成员,则可以处理路径分隔字符的本地化以及其他与路径相关的警告。 以下代码提供深度(包括根)。 对于糟糕的字符串而言,它并不健壮,但这对你来说是一个开始。

 int depth = 0; do { path = Path.GetDirectoryName(path); Console.WriteLine(path); ++depth; } while (!string.IsNullOrEmpty(path)); Console.WriteLine("Depth = " + depth.ToString()); 

如果目录末尾有反斜杠,则会得到与其不同的答案。 这是解决问题的有力方案。

 string pathString = "C:\\temp\\" var rootFolderDepth = pathString.Split(Path.DirectorySeparatorChar).Where(i => i.Length > 0).Count(); 

这将返回路径长度2.如果在没有where语句的情况下执行此操作,则如果省略最后一个分隔符,则路径长度为3或路径长度为2。