Joe
Joe

Reputation: 51

How to count the number of files in a directory AND its sub directories

I am creating a program to count the number of files in a directory and display the total when needed. So far it can count the total number of files in the directory but i would like to know how to edit my current code so it also counts the files within sub directories.

This is just a basic c# application. I am sure there is an easy way to do this but i am a beginner and cant seem to find the code i need to do so.

 System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("sourcePath");
        int count = dir.GetFiles().Length;

The expected results of the code come out well and show the total number of files in the directory. I just need to edit it so it includes sub directories and their files

Upvotes: 5

Views: 9886

Answers (4)

Perfect28
Perfect28

Reputation: 11317

The fastest way is to perform a single EnumerateFileSystemInfos for both directory and file Count as browsing the file system is expensive.

var fileAndDirectoriesCount = new DirectoryInfo(@"sourcePath")
        .EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
        .Count();

If you want to get it separately :

var res = new DirectoryInfo(@"sourcePath")
        .EnumerateFileSystemInfos("*", SearchOption.AllDirectories)
        .GroupBy(s => s is DirectoryInfo)
        .ToDictionary(s => s.Key, s => s.Count());

var directoryCount = res.ContainsKey(true) ? res[true] : 0;
var fileCount = res.ContainsKey(false) ? res[false] : 0;

Upvotes: 5

Syntax Error
Syntax Error

Reputation: 1640

For a directory count use

var countDirectories = System.IO.Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories).Count();

For a file count use

var countFiles = System.IO.Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories).Count();

Then you can add them together, if needed.

Upvotes: 9

Ionut Radu
Ionut Radu

Reputation: 29

Duplicate: Counting the number of files in a folder in c#

Solution: int fileCount = Directory.GetFiles(@"c:\MyDir\", "*.*", SearchOption.AllDirectories).Length;

Upvotes: 1

Johnny
Johnny

Reputation: 9509

Try this:

int fileCount = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories).Count();
int subDirCount = Directory.EnumerateDirectories(path, SearchOption.AllDirectories).Count();
int total = fileCount + subDirCount;

Upvotes: 5

Related Questions