C# - 从 Directory.GetDirectories() 和 Directory.GetFiles() 中排除目录和文件

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

我需要对指定目录路径中的文件和目录进行计数。但我想排除 .git 文件夹和该文件夹内的文件被计算在内。我试过了 -

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

为了排除 .git,我可以写 -

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?

据我所知,GetDirectories() 仅处理文件夹而不处理文件,而 GetFiles() 仅处理文件而不关心 GetDirectories() 排除的目录。

您可以执行以下操作。代码中包含评论

// List of Folders to be ignore, .git ones
var foldersToIgnore = Directory.GetDirectories(path,".git",SearchOption.AllDirectories);
// list of files, excludes ones in .git folder
var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
             .Where(x=>!foldersToIgnore.Any(c=>x.StartsWith(c)));
var directories = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories)
             .Where(x=>!foldersToIgnore.Any(c=>x.StartsWith(c)));
// Count
var maxCount = files.Count() + directories.Count();

您可以尝试这个解决方案:

var pathToIgnore = loadedDirectoryPath + ".git";
int count =
    Directory.GetFiles(loadedDirectoryPath, "*.*", SearchOption.AllDirectories).Where(d => !d.StartsWith(pathToIgnore))
    .Concat(Directory.GetDirectories(loadedDirectoryPath, "*.*", SearchOption.AllDirectories).Where(d => !d.StartsWith(pathToIgnore)))
    .ToArray()
    .Count();

请注意,此解决方案只能让您指定一个要排除的文件夹,但调整它以适用于要排除的多个文件夹是微不足道的。

让我知道它是否有用。

这个怎么样:

    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();

正如 MSDN 所述 here:

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

因此,您最好执行以下操作:

var directory = new DirectoryInfo(directoryPath);
var filesCount = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).Count(file => !file.DirectoryName.Contains(".git"));