Search code examples
c#visual-studioopenfiledialog

Excluding file extensions from open file dialog in C#


I am trying to put a filter on my C# openFileDialog that excludes certain file extensions. For example I want it to show all files in a directory that are not .txt files.

Is there a way to do this?


Solution

  • There is no direct way to do this using the BCL OpenFileDialog.

    I can think of a couple of options:

    1) Make a filter that just has all of the types you do want to support. This would be my recommendation, since that's the most common way of going about this type of operation.

    2) Use something along the lines of this custom OpenFileDialog implementation. You could then override the OnFileNameChanged() method to potentially disable the "Open" button if the selected file has a .txt extension.

    3) Let the user pick a .txt file, throw up an error dialog, and reopen the file dialog. This feels clunky and not too great to me, though....