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

标签 c# file-io getfiles getdirectories

我需要对指定目录路径中的文件和目录进行计数。但我想排除 .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/

相关文章:

c++ - 测试行尾和空白

ruby-on-rails - 通过单击按钮完成文件选择时如何测试文件字段?

c# - 如何访问 "Documents and Settings"文件夹?

c# - 从代码文件动态设置控件的属性

c# - Linq 检查字段类型是数字还是字符串

c# - 如何将 'Name' header 添加到 EmailMessage 中的嵌入图像

java - Spring 集成1.0 RC2 : Streaming file content?

f# - 在F#: How do I obtain a list of the filenames in a directory; expected unit have string中

c# - 如何获取文件的最后修改日期?

javascript - WKWebView.EvaluateJavaScript 永远不会返回