Search code examples
c#winformsfilterfilteringopenfiledialog

How to filter *.abc from *.abcd files when using OpenFileDialog?


I have created an OpenFileDialog object, called openFileDialog.

When calling openFileDialog.ShowDialog I want to be able to select files having only the extension ".abc" and not ".abcd".

Using the property:

this.openFileDialog.Filter = "*.abc";

does not work. ".abcd" files can also be selected.

Here is the full code:

var openFileDialog = GetOpenFileDialog("abc",
                                       "*.abc",
                                       "anything (*.abc)|*.abc",
                                       "Select abc file to import...");

if (openFileDialog.ShowDialog() == DialogResult.OK)
{ DoJob(); }          

Where GetOpenFileDialog is:

private OpenFileDialog GetOpenFileDialog(string defaultExt, string fileName, string filter, string title)
    {
        return new OpenFileDialog
            {
                DefaultExt = defaultExt,
                FileName = fileName,
                Filter = filter,
                Title = title,
            };
    }

I would appreciate any help. Thanks!


Solution

  • Use the filter option of the OpenFileDialog

    this.openFileDialog.Filter = "abc files (*.abc)|*.abc"