Search code examples
c#file-iogetfilesgetdirectories

C# - Exclude directories and files from Directory.GetDirectories() and Directory.GetFiles()


I need to count files and directories inside a specified directory path. But I want to exclude .git folder and files inside this folder from being counted. I tried -

int maxCount = Directory.GetFiles(loadedDirectoryPath, "*.*", SearchOption.AllDirectories).Length + Directory.GetDirectories(loadedDirectoryPath, "*.*", SearchOption.AllDirectories).Length;

And for excluding .git, I can write -

Directory.GetDirectories(loadedDirectoryPath, "*.*", SearchOption.AllDirectories).Where(item => !item.EndsWith(".git")).ToArray().Length;

This will exclude .git directory, But how can I prevent files (present inside .git directory) being counted?

As per my knowledge, GetDirectories() deals with only folders not with files and GetFiles() deals only with files without caring what directories excluded by GetDirectories().


Solution

  • what about this:

        var all = Directory.GetFileSystemEntries(path, "*.*",SearchOption.AllDirectories);
        var allCount = all.Count();
        var noGit = all.Where(p =>  !p.Contains(@"\.git\") && !p.EndsWith(@"\.git")).ToArray();
        var noGitCount = noGit.Count();