如何使用文件扩展名的多个条件搜索文件 [英] how search file with multiple criteria of extension of file

查看:159
本文介绍了如何使用文件扩展名的多个条件搜索文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于搜索文件以及如何搜索具有文件扩展名的任何文件的代码.例如Office文件{docx,pptx,xlsx,pdf},媒体文件{mp3,mp4,mkv,avi},图像文件{jpg,png}. 谢谢

I have code for to search file and how to search any files with multiple extension of file searching.Like Office file {docx,pptx,xlsx,pdf} , media file{mp3,mp4,mkv,avi} , image file {jpg,png}. Thanks

代码:

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).";
        }

推荐答案

为什么不能为同一个扩展创建

Why not you can create a Extension for the same

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));
}

并像这样使用它 用法:

and use it like Usage:

dInfo.GetFilesByExtensions(".jpg",".exe",".gif");

礼貌:具有多个扩展名的GetFiles

这篇关于如何使用文件扩展名的多个条件搜索文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆