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

AR.*_*AR. 11 .net c# directory

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

int folderDepth = 0;
string tmpPath = startPath;

while (Directory.GetParent(tmpPath) != null) 
{
    folderDepth++;
    tmpPath = Directory.GetParent(tmpPath).FullName;
}
return folderDepth;
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*ier 12

脱离我的头顶:

Directory.GetFullPath().Split("\\").Length;
Run Code Online (Sandbox Code Playgroud)

  • 对于其他有效的序列,例如C:\ Folder\..\boot.ini,将被破坏.或者,对于UNC网络路径,例如\\ server\share\file.并且,您应该使用Path.DirectorySeperatorCharacter和Path.AltDirectorySeperatorCharacter. (5认同)
  • @Joey:我认为你的意思是[`System.IO.Path.DirectorySeparatorChar`](https://msdn.microsoft.com/en-us/library/system.io.path.directoryseparatorchar(v = vs.110). ASPX).有点令人困惑的是,[`System.IO.Path.PathSeparator`](https://msdn.microsoft.com/en-us/library/system.io.path.pathseparator%28v=vs.110%29.aspx)指的是到环境变量中的separator _between_ paths,例如`%PATH%`. (2认同)
  • @ mklement0:你是对的。令人惊讶的是,在过去的八年中,没有人去纠正它。 (2认同)

GôT*_*ôTô 9

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

 Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length;
Run Code Online (Sandbox Code Playgroud)


Jef*_*dge 5

我一直很喜欢递归解决方案。效率低下,但很有趣!

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;
}
Run Code Online (Sandbox Code Playgroud)

我喜欢用 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;
}
Run Code Online (Sandbox Code Playgroud)

美好的时光,美好的时光……