Search code examples
c#directorydirectory-structure

Are there C# methods to get the number of folders up or down from a reference path?


I am looking for a simple API set of methods that find out if a folder is a subdirectory of another folder, and how many steps there are between this. Something like:

int numberOfFoldersDown(string parentFolder, string subfolder)  { ... }

It seems quite useful, though tedious to write, so I thought it should be somewhere in the System.IO.Path or System.IO.Directory assemblies, but I can't find any helpful methods there. Are these functions available, or should I write them myself?


Solution

  • Nothing built-in AFAIK.

    Here's some recursive example that uses both Path and Directory methods:

    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine(NumberOfFoldersDown(@"c:\temp\", @"c:\temp\"));                   // 0
            Console.WriteLine(NumberOfFoldersDown(@"c:\temp\", @"c:\temp\zz\"));                // 1
            Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\", @"c:\temp\zz\"));               // -1
            Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\", @"c:\temp2\zz\hui\55\"));       // 3
            Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\zz\", @"c:\temp2\zz\hui\55\"));    // 2
    
            Console.Read();
        }
    
        public static int NumberOfFoldersDown(string parentFolder, string subfolder)
        {
            int depth = 0;
            WalkTree(parentFolder, subfolder, ref depth);
            return depth;
        }
    
        public static void WalkTree(string parentFolder, string subfolder, ref int depth)
        {
            var parent = Directory.GetParent(subfolder);
            if (parent == null)
            {
                // Root directory and no match yet
                depth = -1;
            }
            else if (0 != string.Compare(Path.GetFullPath(parentFolder).TrimEnd('\\'), Path.GetFullPath(parent.FullName).TrimEnd('\\'), true))
            {
                // No match yet, continue recursion
                depth++;
                WalkTree(parentFolder, parent.FullName, ref depth);
            }
        }
    }