System.Windows.Forms.SaveFileDialog does not enforce default extension

Pierre Arnaud picture Pierre Arnaud · Oct 21, 2009 · Viewed 11.3k times · Source

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.

Answer

Thomas Levesque picture Thomas Levesque · Nov 2, 2009

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;
    }
}