Search code examples
c#stringlinqfilteropenfiledialog

Apply file filters to string [] of filenames , without opening OpenFileDialog


I want to apply a filter on string [] of FileNames that i get from Directory.GetFiles() without opening it in OpenFileDialog.

Is there any way I can apply all these filters (that i usually would apply to OpenFileDialog) e.g:

openFileDialog.Filter = "Bitmap Images (*.bmp)|*.bmp|" +
                          "JPEG Images (*.jpeg, *.jpg)|*.jpeg;*.jpg|" +
                          "PNG Images (*.png)|*.png|" + ...;

to the string [].

I basically want to select Folder from FolderBrowserDialog and select only selected files from the Folder - was trying find some way to do this silently(setting parameters to OpenFileDialog but not opening it ).

I just tried the following .:

OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = folderdialog.SelectedPath; // here I get my folder path 
            openFileDialog.Filter = "Bitmap Images (*.bmp)|*.bmp|" +
                          "JPEG Images (*.jpeg, *.jpg)|*.jpeg;*.jpg|" +
                          "PNG Images (*.png)|*.png";                
            string [] fnms = openFileDialog.FileNames; // I wished this string arry to get poplulated with filtered file list - but doh! Obviously it didn't.

Can anyone help me with find a solution to this. Is there any way to invoke OpenFiledDialog silently ? Or will there be any LINQ query for this problem or anything as such .? [I'm a novice - yet learner]

Any help will be much appreciated. Thanks in advance


Solution

  • I don't think calling Directory.GetFiles more than once will be a good idea because it is an IO operation. I recommend that you do something like:

    static string[] GetFiles(string directory, params string[] extensions)
    {
        var allowed = new HashSet<string>(extensions, StringComparer.CurrentCultureIgnoreCase);
    
        return Directory.GetFiles(directory)
                        .Where(f => allowed.Contains(Path.GetExtension(f)))
                        .ToArray();
    }
    
    static void Main(string[] args)
    {
        string[] files = GetFiles(@"D:\My Documents", ".TXT", ".docx");
        foreach(var file in files)
        {
            Console.WriteLine(file);
        }
    }