如何搜索具有多个文件扩展名条件的文件
本文关键字:文件 扩展名 条件 何搜索 搜索 | 更新日期: 2023-09-27 17:58:36
我有搜索文件的代码,以及如何使用文件搜索的多扩展名搜索任何文件。像Office文件{docx,pptx,xlsx,pdf},媒体文件{mp3,mp4,mkv,avi},图像文件{jpg,png}。感谢
代码:
public void SearchFile(string folder, string KeyWord, DataGridView TableName, ref Label Result, ref long Count)
{
string[] row;
foreach (string file in Directory.GetFiles(folder, "*" + KeyWord + "*doc")) // <== Multiple Extension Searching
{
FileInfo fi = new FileInfo(file);
double Lenght = fi.Length / 1024;
row = new string[] { fi.Name, Lenght.ToString() + " KB", fi.LastAccessTime.Year.ToString(), fi.FullName };
TableName.Rows.Add(row);
number += 1;
}
foreach (string subDir in Directory.GetDirectories(folder))
{
try
{
SearchFile(subDir , KeyWord, TableName, ref Result, ref Count);
}
catch (UnauthorizedAccessException) { }
}
Count = Number;
Result.Text = "File Keyword '" + KeyWord + "', Not Found " + number.ToString() + " (file).";
}
为什么不能为同一创建一个扩展
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
并像使用它一样用法:
dInfo.GetFilesByExtensions(".jpg",".exe",".gif");
提供:具有多个扩展名的GetFiles