问题
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.
回答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.
来源:https://stackoverflow.com/questions/55745253/savefiledialog-should-i-use-the-filterindex-property-or-the-extension-of-the-fil