C# 获取给定路径的文件夹深度的最佳方法?
我正在做一些需要遍历文件系统的事情,对于任何给定的路径,我需要知道我在文件夹结构中的“深度”。 这是我目前正在使用的:
int folderDepth = 0;
string tmpPath = startPath;
while (Directory.GetParent(tmpPath) != null)
{
folderDepth++;
tmpPath = Directory.GetParent(tmpPath).FullName;
}
return folderDepth;
这可行,但我怀疑有更好/更快的方法吗? 非常感谢任何反馈。
I'm working on something that requires traversing through the file system and for any given path, I need to know how 'deep' I am in the folder structure. Here's what I'm currently using:
int folderDepth = 0;
string tmpPath = startPath;
while (Directory.GetParent(tmpPath) != null)
{
folderDepth++;
tmpPath = Directory.GetParent(tmpPath).FullName;
}
return folderDepth;
This works but I suspect there's a better/faster way? Much obliged for any feedback.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
从我的头顶上掉下来:
Off the top of my head:
我对此已经很晚了,但我想指出保罗·索尼尔的答案可能是最短的,但应该是:
I'm more than late on this but I wanted to point out Paul Sonier's answer is probably the shortest but should be:
我一直很喜欢递归解决方案。 效率低下,但很有趣!
我喜欢用 C# 编写的 Lisp 代码!
这是我更喜欢的另一个递归版本,并且可能更有效:
好时光,好时光......
I'm always a fan the recursive solutions. Inefficient, but fun!
I love the Lisp code written in C#!
Here's another recursive version that I like even better, and is probably more efficient:
Good times, good times...
如果您使用 Path 类的成员,则可以处理路径分隔字符的本地化和其他与路径相关的注意事项。 以下代码提供深度(包括根)。 它对坏字符串等的鲁棒性并不强,但它对你来说是一个开始。
If you use the members of the
Path
class, you can cope with localizations of the path separation character and other path-related caveats. The following code provides the depth (including the root). It's not robust to bad strings and such, but it's a start for you.假设您的路径已经过验证,在 .NET 3.5 中您还可以使用 LINQ 在 1 行代码中完成此操作...
Assuming your path has already been vetted for being valid, in .NET 3.5 you could also use LINQ to do it in 1 line of code...
如果目录末尾有反斜杠,您会得到与没有反斜杠时不同的答案。 这是该问题的可靠解决方案。
这将返回路径长度 2。如果在不使用 where 语句的情况下执行此操作,则会得到路径长度 3,如果省略最后一个分隔符,则会得到路径长度 2。
If the directory has a backslash at the end, you get a different answer than when it doesn't. Here's a robust solution to the problem.
This returns a path length of 2. If you do it without the where statement, you get a path length of 3 or a path length of 2 if you omit the last separator character.
也许有人还需要一些性能测试......
https://cc.davelozinski。 com/c-sharp/fastest-way-count-number-times-character-occurrs-string
和
https://cc.davelozinski。 com/c-sharp/c-net-fastest-way-count-substring-occurrences-string
Maybe someone need also some performance testing...
https://cc.davelozinski.com/c-sharp/fastest-way-count-number-times-character-occurs-string
and
https://cc.davelozinski.com/c-sharp/c-net-fastest-way-count-substring-occurrences-string