tags:

views:

3015

answers:

4

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.

+3  A: 

Off the top of my head:

Directory.GetFullPath().Split("\\").Length;
McWafflestix
Like the idea alot! Just a quick note, Length is a property not a method.
BFree
Whoops, good point; I'll edit that...
McWafflestix
Would be broken for otherwise valid sequences such as C:\Folder\..\boot.ini. Or, for UNC network paths such as \\server\share\file. And, you should probably use Path.DirectorySeperatorCharacter and Path.AltDirectorySeperatorCharacter.
Mark Brackett
Thanks McWafflestix (great name!). I had considered this, but how to handle cases where the backslash isn't the path separator? Would that even be an issue?
AR
AR: You can still use System.IO.Path.PathSeparator instead of \
Joey
A: 

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.

        int depth = 0;
        do
        {
            path = Path.GetDirectoryName(path);
            Console.WriteLine(path);
            ++depth;
        } while (!string.IsNullOrEmpty(path));

        Console.WriteLine("Depth = " + depth.ToString());
Jeff Yates
A: 

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

Console.WriteLine(@"C:\Folder1\Folder2\Folder3\Folder4\MyFile.txt".Where(c => c = @"\").Count);

A: 

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

Jeffrey L Whitledge