【问题标题】:how to get count of file with multiple keyword in GetFiles如何在 GetFiles 中获取具有多个关键字的文件数
【发布时间】:2019-12-11 07:04:42
【问题描述】:

我想显示某个文件夹中有多少具有特定扩展名(jpg、jpeg、png、psd 等)的文件。但也必须带有特定的关键字,如“10*”或“1A*”。首先,我只制作了一些带有扩展名的代码,然后我得到了某个文件夹中文件的数量。但我尝试制作第二个代码以获取具有特定名称和特定扩展名但遇到困难的文件的数量。

我尝试在 getfiles 之后添加“where”,但仍然不能并得到错误。

这是第一个代码:

DirectoryInfo folder = new DirectoryInfo(@"" + folderpath );
string extension = "jpg";
int count = folder.GetFiles("*." + extension, SearchOption.TopDirectoryOnly).Length;

这里是第二个带有关键字和扩展名的代码:

DirectoryInfo folder = new DirectoryInfo(@"" + folderpath );
string extension = "jpg";
string keyword = "1A";
int count = folder.GetFiles( keyword + "*", SearchOption.TopDirectoryOnly).Where(s => s.EndsWith("." + format )).Count;

结果还是错误。我需要更改哪些内容才能使用关键字和扩展名使代码正常工作?

【问题讨论】:

  • DirectoryInfo.GetFiles 返回FileInfo[],但您尝试应用过滤器Where(fi => fi.EndsWith...)。请注意,FileInfo 实例不是string。所以也许你想使用Where(fi => fi.Name.EndsWith...)
  • @TimSchmelter,谢谢,你给了我最好的线索,我使用你的第一个陈述,它的工作原理:)

标签: c# file keyword


【解决方案1】:

您可以使用 LINQ 完成所有操作:

string[] prefixes = new[] { "10", "1A" };
string[] suffixes = new[] { "jpg", "jpeg", "png", "psd" };

int count = folder.GetFiles().Count(f => prefixes.Any(p => f.Name.StartsWith(p)) && suffixes.Any(s => f.Extension == s));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2011-10-25
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    相关资源
    最近更新 更多