我需要对指定目录路径中的文件和目录进行计数。但我想排除 .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();
关于C# - 从 Directory.GetDirectories() 和 Directory.GetFiles() 中排除目录和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60447545/