If you want to know how many files exist in a certain directory including all files of subdirectories, you can use this function. There is one exception. It will omit the system restricted file which can not be accessed. Recursively call itself to calculate subdirectories.

Code Snippet

public static int GetTotalFiles(this DirectoryInfo di) 
        int total = 0;

        total += di.GetFiles().Length;

        DirectoryInfo[] dis = di.GetDirectories();

        foreach (DirectoryInfo d in dis)
            total += d.GetTotalFiles();

        return total;
        return 0;

Sample Usage

DirectoryInfo di = new DirectoryInfo(@"C://MyFolder");
int fileCount = di.GetTotalFiles();

author's photo

Author : Blue Cloud

Just a normal software developer who love to write code. Developing professional software since 1999. After working in the software industry for many years, I've started my own website to share knowledges and experiences.

blog comments powered by Disqus