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

后端 未结 7 2207
野趣味
野趣味 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 19:13

    If the directory has a backslash at the end, you get a different answer than when it doesn't. Here's a robust solution to the problem.

    string pathString = "C:\\temp\\"
    var rootFolderDepth = pathString.Split(Path.DirectorySeparatorChar).Where(i => i.Length > 0).Count();
    

    This returns a path length of 2. If you do it without the where statement, you get a path length of 3 or a path length of 2 if you omit the last separator character.

提交回复
热议问题