سؤال

I want to use a file dialog in a WPF program. I'm setting the Filter property to a specific extension, but the user can just type "* . *" in the file name line and thus bypass the filter. Is there a way to stop a user from doing it and keep the file filter no matter what he types?

هل كانت مفيدة؟

المحلول

You can't prevent the user from typing a file with a different extension into the box.

But you can test the file extension of the selected file, after the selection has been made:

FileDialog fd = new OpenFileDialog();
fd.Filter = "*.txt|*.txt";
fd.ShowDialog();

if (Path.GetExtension(fd.FileName).ToLower() != ".txt")
    MessageBox.Show("Choose a text file!");

نصائح أخرى

With WPF you have to use the standard Windows common dialogs (basically the normal WinForms ones that wraps the Win32API), and the normal Windows dialog does not prevent that in any way that the user types in any file name, or selects an extension outside the filters you initially select, as the filters are merely a suggestion for the user, but don't enforce anything.

The most you can do with the built-in Windows dialogs is to provide filters, which the user will always be able to override by typing anything or by choosing another filter (BTW, this is why I always provide a "." filter in addition to the correct one).

May I ask why you want to forbid anything outside a predefined extension? Remember that an extension is just part of the file name, an indicator of its contents but not a hard rule that prevents it to contain anything else. The user might want to select files with a different extension if he has for example a text file with a more exotic extension, or a malicious user may place bad content in a file with .txt.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top