Number of folder inside a directory

How do I know the number of folders inside a directory?

I try using System.IO.Directory but no luck.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’ve got a couple of options:

int directoryCount = System.IO.Directory.GetDirectories(@"c:yourpath").Length

var directoryInfo = new System.IO.DirectoryInfo(@"c:yourpath");
int directoryCount = directoryInfo.GetDirectories().Length;

If you need to do other things with them, and you’re using .NET 4, you can use the DirectoryInfo.EnumerateDirectories() function for performance reasons as well.

So yeah, lots of options. If you’re still having problems, you might want to let us know what didn’t work when using System.IO.Directory.

Method 2



of course instead of @"C:" you use whatever path you want to know the sub-directory count for. The method also has overloads to allow searching for a specific pattern and searching recursively.

Method 3

To Count files in folder:-

string[] My_file = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files Found: " + My_file.Length.ToString());

To Count Folder in directories:-
MessageBox.Show("Folder Count:" + Directory.GetDirectories(folderBrowserDialog1.SelectedPath).Length.ToString(), "Message");

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x