1

I have 1 directory. In this directory it contains 9folders(subdirectory). Each folder(subdirectory) contains a variable number of folders(subsubdirectory), and also in (subsubdirectory) it contains some folder....so on.... I tried this method but i dont know how to expand it because of variable number of subdirectory.

        public static long GetDirectoryNumberOfFiles(string directory, bool includeSubDir)
        {
            long numberFiles = Directory.GetFiles(@directory).Length;

            string[] subfolderEntries = Directory.GetDirectories(directory);//result 9

            //i tried this, but without luck.
            var dirInfo =new DirectoryInfo(directory);
            int dirCount = dirInfo.GetDirectories().Length;//result 9


            if (includeSubDir)
            {
              for (int i = 0; i < subfolderEntries.Count(); i++)
              { numberFiles += Directory.GetFiles(subfolderEntries[i]).Length; }//result 38
            }

          return numberFiles;
    }

When I right clicked the directory, it contains 23,026 files and 440folders. But with this method, i got 38files and 9folders. I know it just count the subdirectories but not all folders inside directory.

1

2 Answers 2

3

Try this

int directoryCount = Directory.GetDirectories("yourpath", "*", SearchOption.AllDirectories).Length;
int fileCount = Directory.GetFiles("yourpath", "*", SearchOption.AllDirectories).Length;

SearchOption is important to use here. See MSDN for more information https://msdn.microsoft.com/en-us/library/ms143314(v=vs.110).aspx

0

Use EnumerateDirectories(String, SearchOption), EnumerateFiles(String, SearchOption) and system directory and system file methods if need DirectoryInfo

Not the answer you're looking for? Browse other questions tagged or ask your own question.