How do I know the number of folders inside a directory?
I try using System.IO.Directory
but no luck.
Using the ls Command. The ls command lists the directories and files contained in a directory. The ls command with the -lR options displays the list (in long format) of the sub-directories in the current directory recursively.
To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1. It doesn't count dotfiles.
Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.
Directories contain files, subdirectories, or a combination of both. A subdirectory is a directory within a directory. The directory containing the subdirectory is called the parent directory.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With