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)
我迟到了,但我想指出Paul Sonier的回答可能是最短的,但应该是:
Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length;
Run Code Online (Sandbox Code Playgroud)
我一直很喜欢递归解决方案。效率低下,但很有趣!
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)
美好的时光,美好的时光……