Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

directory

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.

like image 249
AR. Avatar asked Nov 25 '08 00:11

AR.


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.


2 Answers

I'm more than late on this but I wanted to point out Paul Sonier's answer is probably the shortest but should be:

 Path.GetFullPath(tmpPath).Split(Path.DirectorySeparatorChar).Length;
like image 80
GôTô Avatar answered Sep 19 '22 12:09

GôTô


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());
like image 20
Jeff Yates Avatar answered Sep 22 '22 12:09

Jeff Yates