Filter Property

FileDialog.Filter Property


Gets or sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public string Filter { get; set; }

Property Value

Type: System.String

The file filtering options available in the dialog box.

Exception Condition

Filter format is invalid.

For each filtering option, the filter string contains a description of the filter, followed by the vertical bar (|) and the filter pattern. The strings for different filtering options are separated by the vertical bar.

The following is an example of a filter string:

Text files (*.txt)|*.txt|All files (*.*)|*.*

You can add several filter patterns to a filter by separating the file types with semicolons, for example:

Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*

Use the FilterIndex property to set which filtering option is shown first to the user.

The following code example uses the OpenFileDialog implementation of FileDialog and illustrates creating, setting of properties, and showing the dialog box. The example uses the Filter and FilterIndex properties to provide a list of filters for the user. The example requires a form with a Button placed on it and the System.IO namespace added to it.

private void button1_Click(object sender, System.EventArgs e)
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
            if ((myStream = openFileDialog1.OpenFile()) != null)
                using (myStream)
                    // Insert code to read the stream here.
        catch (Exception ex)
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);

.NET Framework
Available since 1.1
Return to top
© 2016 Microsoft