C# WPF - Only allow certain file extensions

2.3k Views Asked by At

I have an OpenFileDialog and I only want to allow .txt as a valid file for the users.

I know I can add a Filter to the OpenFileDialog like so:

var dialog = new OpenFileDialog();
dialog.DefaultExt = ".txt";
dialog.Filter = "Text Files (*.txt)|*.txt";
var result = dialog.ShowDialog();
// Do something with the result

The problem however, is that I can still directly say something like "test.jpg" in the OpenFileDialog and then it opens this uploads this .jpg file. (Obviously it goes wrong somewhere later, but that doesn't matter for now.) I just want to know how I can restrict the user to only add ".txt" files, nothing else? (By directly validation it inside the OpenFileDialog, instead of doing it somewhere later.)

1

There are 1 best solutions below

1
On BEST ANSWER

You cant do that only in OpenFileDialog and even if you could its a bad limitation.

Using the *.txt example there are multiple files extensions that are plain text inside, *.bat or all the codding file extensions *.cs, *.js, etc...

You should not limit the user on what file he can put on it.

For more complex file types if your program cant handle the file passed by the user you should show an error not prevent the user from passing the file.