Keywords: C# | WinForms | OpenFileDialog | File Extensions | Filter Property
Abstract: This article explains how to set the Filter property in C# WinForms OpenFileDialog to support multiple file extensions, including grouping and creating an "All graphics types" option, with detailed examples and explanations.
Introduction
In C# WinForms application development, the OpenFileDialog control is a key tool for file selection. Its Filter property is used to specify selectable file types, but the standard usage often supports only a single extension. However, in practical applications, it is common to include multiple related extensions in one file type group, such as JPG files covering *.jpg and *.jpeg.
Core Method
According to Microsoft official documentation, the Filter property string format for OpenFileDialog is "description|extension list", where the extension list can use semicolons (;) to separate multiple extensions. For example, to support JPG files, it can be set as JPG|*.jpg;*.jpeg, allowing users to filter *.jpg and *.jpeg files when selecting the JPG type.
Example Code
Here is a complete code example demonstrating how to set multiple file extensions and add an "All graphics types" option:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";In this string, each file type group is separated by a pipe (|) between the description and the extension list. The extension list uses semicolons to separate multiple extensions internally. The last part adds the "All Graphics Types" group, which includes all graphic file extensions.
Supplementary Information
In addition to using semicolons to separate extensions, another common format is to display extensions in the description, such as JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg. This format may be clearer in some contexts, but the standard recommendation is to use the semicolon-separated approach to ensure compatibility and consistency.
Conclusion
By properly configuring the Filter property, developers can flexibly support multiple file extensions in OpenFileDialog, thereby enhancing the file selection functionality of applications and improving user experience. Mastering this technique helps efficiently handle file filtering needs in C# WinForms development.