Use file dialog filters in C#


The OpenFileDialog and SaveFileDialog components have a Filter property that lets the user look for specific kinds of files. The property’s value should be a pipe symbol (|) separated list of alternating filter names and patterns. Each pattern can include more than one file matching pattern separated by semi-colons.

This example uses the following Filter (all on one line):

Bitmaps|*.bmp|PNG files|*.png|JPEG files|*.jpg|Picture files|
    *.bmp;*.jpg;*.gif;*.png;*.tif|CS files|*.cs|Project files|
    *.csproj|Program files|*.cs;*.csproj;*.sln;*.suo;*.resx

The parts of the filter are:

  • Bitmaps – *.bmp
  • PNG files – *.png
  • JPEG files – *.jpg
  • Picture files – *.bmp;*.jpg;*.gif;*.png;*.tif
  • CS files – *.cs
  • Project files – *.csproj
  • Program files – *.cs;*.csproj;*.sln;*.suo;*.resx

For example, if the user selects the “Picture files” filter, the dialog lists files with the extensions .bmp, .jpg, .gif, .png, and .tif.

The file selection dialogs also have a FilterIndex property that indicates the currently selected filter. You can set this to initially select a filter. Note, however, that the first filter’s index is 1 instead of the 0 as is usually the case for arrays in .NET.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in dialogs, files and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.