10

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

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

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Pedro de la Cruz
  • 343
  • 1
  • 5
  • 15
  • http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts – Kiquenet Apr 29 '13 at 07:57

3 Answers3

13

You've got a couple of options:

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

or

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.

Tim
  • 14,999
  • 1
  • 45
  • 68
8

Use:

Directory.GetDirectories(@"C:\").Length

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.

SirViver
  • 2,411
  • 15
  • 14
  • 1
    `EnumerateDirectories(…).Count()` could be less memory-consuming, if the number of subdirectories is huge. – svick May 13 '11 at 19:03
  • @svick: Thanks, I didn't know about this. Still stuck on 3.5 at my workplace, so some of the less prominent 4.0 features are lost on me :) – SirViver May 13 '11 at 19:12
1

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");
bajran
  • 1,433
  • 14
  • 23