如何使用多个扩展名标准的搜索文件

时间:2014-04-16 04:54:03

标签: c# search file-extension

我有搜索文件的代码以及如何搜索具有多个文件搜索扩展名的文件。像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).";
        }

1 个答案:

答案 0 :(得分:0)

为什么不能为同一个

创建扩展名
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 with multiple extensions