views:

925

answers:

3

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.

+2  A: 

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.

Darin Dimitrov
+3  A: 

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;
    }
}
Thomas Levesque
A: 

The nearest I've got to this is by using the FileOk event. For example:

dialog.FileOk += openFileDialog1_FileOk;

private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(!dialog.FileName.EndsWith(".foo"))
  { 
     e.Cancel = true;
  }
}

Checkout FileOK Event on MSDN.

Ian