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.
I'm more than late on this but I wanted to point out Paul Sonier's answer is probably the shortest but should be:
Maybe someone need also some performance testing...
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...
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.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.
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.
Off the top of my head: