How can I change the extension of the file name in a SaveFileDialog when the user changes the filter?
-
11-09-2019 - |
Question
We have an SaveFileDialog
in our application, which offers a variety of formats the user can export media in. We determine the user's choice of format using the FilterIndex
property of the SaveFileDialog
. The various formats have different file extensions, so we would like the file name that the user has entered to change extension when the user changes the selected filter. Is this possible, and if so, how?
EDIT: I want this to happen while the dialog is shown, when the user changes the filter, so the user gets feedback on what the filename will be, rather than afterwards when the user closes the dialog. I've tried using a message filter, but it doesn't receive messages for the dialog. I've tried Application.Idle
but that never fires while the dialog is running. I've tried a background thread, but FilterIndex
doesn't get updated until the user closes the dialog.
Solution
As SaveFileDialog can't be inherited, I guess you must build your own, using FileDialog as the base class.
OTHER TIPS
SaveFileDialog changes extension of the file automatically when user changes filter. If you want to process some certain actions for different file formats you can youse something like this:
...
if (saveDialog.ShowDialog() == DialogResult.OK)
{
switch (saveDialog.FilterIndex)
{
case 0:
...
break;
case 1:
...
break;
default:
...
break;
}
}
...
Add your filters:
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|Word files (*.doc)|*.doc";
then:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
switch (saveFileDialog1.FilterIndex)
{
case 1:
saveFileDialog1.FileName = System.IO.Path.ChangeExtension(saveFileDialog1.FileName, "txt");
break;
case 2:
saveFileDialog1.FileName = System.IO.Path.ChangeExtension(saveFileDialog1.FileName, "doc");
break;
}
// Here you would save your file with the filename in saveFileDialog1.FileName.
MessageBox.Show(saveFileDialog1.FileName);
}
Runt it twice, first select "txt files" then "Word files". Enter "test" as the filename.
You will see that the filename is different in both cases: text.txt and test.doc.
If you enter a filename with an extension like "test.htm" then the extension is changed when you switch filter.
If you enter a filename like "test.htm" and DON'T change the filter the switch case takes care of the extension for you.