Question

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).";
        }
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top