SaveFileDialog should I use the FilterIndex property or the extension of the FileName property?
Asked Answered
Y

1

0

The other day I had the following question SaveFileDialog AddExtension doesn't work as expected. Now a follow up question came to my mind.

Should I use the FilterIndex property or the extension of the FileName property of the SaveFileDialog to decide under which file format I want to store the data?

I've the following C# test code:

var dialog = new SaveFileDialog();
dialog.AddExtension = true;
dialog.DefaultExt = "txt";
dialog.Filter = "Text files (*.txt)|*.txt|XML files (*.xml)|*.xml";
dialog.OverwritePrompt = true;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string extension = System.IO.Path.GetExtension(dialog.FileName);
    int filterIndex = dialog.FilterIndex;
}

The documentation quotes that:

You can also use the value of FilterIndex after showing the file dialog to perform special file operations depending upon the filter chosen.

If I use the FilterIndex property it will save for example a text document with an XML extension (Dialog File name = test7.xml, Dialog Save as type = *.txt).

If I use the extension of the FileName then the Save as type of the dialog is ignored.

Yul answered 18/4, 2019 at 11:40 Comment(0)
P
1

There's a difference between the file's name and its format.

The FilterIndex property can specify the format of the file, but the FileName should specify how they want the file named. These can be different.

Beware, however. If your list of formats includes an option for "All Files (*.*)", you run into an issue with the default format. Is that format obvious to the user?

My suggestion to you, in short, is to use the drop-down list for the format, and the FileName for just that. Let a user save a CSV file with a .TXT extension.

Pearsall answered 18/4, 2019 at 11:52 Comment(1)
I agree with you. MS Word adds for those cases double extension (see my other question). On the other hand MS Wordpad uses the extension of the filename. By the way: there is no plan that my SaveFileDialog has no All Files option.Yul

© 2022 - 2024 — McMap. All rights reserved.