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

后端 未结 7 2205
野趣味
野趣味 2021-02-19 18:29

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 cu

7条回答
  •  逝去的感伤
    2021-02-19 18:56

    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());
    

提交回复
热议问题