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

Off the top of my head:

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

I'm more than late on this but I wanted to point out Paul Sonier's answer is probably the shortest but should be:

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

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...

Tags:

C#

.Net

Directory