how search file with multiple criteria of extension of file

梦想与她 提交于 2019-12-11 21:37:59

问题


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

Code :

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:


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

courtesy :GetFiles with multiple extensions



来源:https://stackoverflow.com/questions/23100271/how-search-file-with-multiple-criteria-of-extension-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!