SaveFileDialog 我应该使用 FilterIndex 属性 还是 FileName 属性 的扩展名?

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

前几天我有以下问题SaveFileDialog AddExtension doesn't work as expected。现在我想到了一个后续问题。

我应该使用 FilterIndex property or the extension of the FileName property of the SaveFileDialog 来决定我想以哪种文件格式存储数据?

我有以下 C# 测试代码:

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

文档引用:

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

如果我使用 FilterIndex 属性 它将保存例如一个扩展名为 XML 的文本文档(Dialog File name = test7.xml、Dialog Save as type = *.txt) .

如果我使用 FileName 的扩展名,那么对话框的 Save as type 将被忽略。

文件名和格式不同。

FilterIndex 属性 可以指定文件的格式,但FileName 应该指定文件的命名方式。这些可以不同。

但是要小心。如果您的格式列表包含“All Files (*.*)”选项,您 运行 就会遇到默认格式的问题。这种格式对用户来说是显而易见的吗?

简而言之,我的建议是使用下拉列表作为格式,并使用文件名。让用户保存扩展名为 .TXT 的 CSV 文件。