C# Best way to get folder depth for a given path?

2020-07-03 06:51发布

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.

7条回答
Lonely孤独者°
2楼-- · 2020-07-03 07:31

I'm always a fan the recursive solutions. Inefficient, but fun!

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;
}

I love the Lisp code written in C#!

Here's another recursive version that I like even better, and is probably more efficient:

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;
}

Good times, good times...

查看更多
登录 后发表回答