I am trying to make SaveFileDialog
and FileOpenDialog
enforce an extension to the file name entered by the user. I've tried using the sample proposed in question 389070 but it does not work as intended:
var dialog = new SaveFileDialog())
dialog.AddExtension = true;
dialog.DefaultExt = "foo";
dialog.Filter = "Foo Document (*.foo)|*.foo";
if (dialog.ShowDialog() == DialogResult.OK)
{
...
}
If the user types the text test
in a folder where a file test.xml
happens to exist, the dialog will suggest the name test.xml
(whereas I really only want to see *.foo
in the list). Worse: if the user selects test.xml
, then I will indeed get test.xml
as the output file name.
How can I make sure that SaveFileDialog
really only allows the user to select a *.foo
file? Or at least, that it replaces/adds the extension when the user clicks Save
?
The suggested solutions (implement the FileOk
event handler) only do part of the job, as I really would like to disable the Save
button if the file name has the wrong extension.
In order to stay in the dialog and update the file name displayed in the text box in the FileOk
handler, to reflect the new file name with the right extension, see the following related question.
The SaveFileDialog component allows users to browse the file system and select files to be saved. The dialog box returns the path and name of the file the user has selected in the dialog box. However, you must write the code to actually write the files to disk.
The extension added to a file name depends on the currently selected file filter and the value of the CheckFileExists property. If the CheckFileExists property is true , the dialog box adds the first extension from the current file filter that matches an existing file.
AddExtension Property: "Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension."
We have set the Filter property of the SaveFileDialog control to display text file types with . txt extensions only. Write some text in the text box and click on the Save Comment button to save the text as a text file in your computer.
You can handle the FileOk
event, and cancel it if it's not the correct extension
private saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
if (!saveFileDialog.FileName.EndsWith(".foo"))
{
MessageBox.Show("Please select a filename with the '.foo' extension");
e.Cancel = true;
}
}
AFAIK there's no reliable way to enforce a given file extension. It is a good practice anyway to verify the correct extension, once the dialog is closed and inform the user that he selected an invalid file if the extension doesn't match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With