Click here to Skip to main content
15,896,320 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
myDir = GetMyDirectoryForTheExample ();
int count = myDir.GetFiles().Length;
Posted
Comments
Andy Lanng 16-Apr-15 6:56am    
You will have to iterate through each sub-directory within the given directory and sum the results
Member 11527624 16-Apr-15 9:53am    
could u please provide me with any code???

1 solution

This is a recursive method

C#
private int GetFileCount(DirectoryInfo directoryInfo, bool includeSubFolders = true)
{
    int filesInThisFolder = 0;
    if (directoryInfo.Exists)
    {
        filesInThisFolder = directoryInfo.GetFiles().Count();
    }
    if(includeSubFolders)
        filesInThisFolder += directoryInfo.GetDirectories().Sum(di => GetFileCount(di));

    return filesInThisFolder;
}


1. Pass a new DirectoryInfo(path) to GetFileCount
2. In that one directory, it counts the files
3. In that one directory, it gets a list of subdirectories
4/1. It Passes a new DirectoryInfo(path) to GetFileCount
...
5. If there are no subdirectories (or no more subdirectories) it returns the sum of files.


EDIT: without linq


C#
private int GetFileCount(DirectoryInfo directoryInfo, bool includeSubFolders = true)
        {
            int filesInThisFolder = 0;
            if (directoryInfo.Exists)
            {
                filesInThisFolder = directoryInfo.GetFiles().Count();
            }
            if (includeSubFolders)
                foreach (DirectoryInfo info in directoryInfo.GetDirectories())
                {
                    filesInThisFolder += GetFileCount(info);
                }

            return filesInThisFolder;
        }
 
Share this answer
 
v2
Comments
Member 11527624 17-Apr-15 1:28am    
thank u :)
Member 11527624 17-Apr-15 1:55am    
filesInThisFolder += directoryInfo.GetDirectories().Sum(di => GetFileCount(di));
I am getting the error at di and > like invalid expressin term.What is that mean?
Andy Lanng 17-Apr-15 4:00am    
This is a linq expression. the di=>blah is known as a lamda function, but I won't go into techie details about that here. I'll update the answer with a non-linq solution
You should look into linq. IT IS AWESOME! 'nuff said ^_^

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900