问题
var dlg = new SaveFileDialog();
dlg.FileName = "graph";
dlg.DefaultExt = ".bmp";
dlg.Filter = "PNG|*.png|DOT|*.dot|Windows Bitmap Format|*.bmp|GIF|*.gif|JPEG|*.jpg|PDF|*.pdf|Scalable Vector Graphics|*.svg|Tag Image File Format|*.tiff";
The extension always defaults to .png
. It seems the DefaultExt
is ignored if there is a Filter
; then it just defaults to the first option in the list.
Is there a way to force it to actually respect the default ext?
回答1:
You should set FilterIndex
property instead of DefaultExt
. If you still want to use DefaultExt
, you can convert it to proper filter index manually:
public static void UseDefaultExtAsFilterIndex(FileDialog dialog)
{
var ext = "*." + dialog.DefaultExt;
var filter = dialog.Filter;
var filters = filter.Split('|');
for(int i = 1; i < filters.Length; i += 2)
{
if(filters[i] == ext)
{
dialog.FilterIndex = 1 + (i - 1) / 2;
return;
}
}
}
var dlg = new SaveFileDialog();
dlg.FileName = "graph";
dlg.DefaultExt = ".bmp";
dlg.Filter = "PNG|*.png|DOT|*.dot|Windows Bitmap Format|*.bmp|GIF|*.gif|JPEG|*.jpg|PDF|*.pdf|Scalable Vector Graphics|*.svg|Tag Image File Format|*.tiff";
UseDefaultExtAsFilterIndex(dlg);
dlg.ShowDialog();
回答2:
DefaultExt is the extension that will be used if the user selects a file name with no extension (atleast that's my understanding from reading the description from MSDN).
When the user of your application specifies a file name without an extension, the FileDialog appends an extension to the file name.
You may have to make bmp
the first item in the filter list.
回答3:
There is different explanations depending on API, but seem to work similarly;
DefaultExt
is used when the user selects a file name with no extension AND selected filter is a wildcard filter, like (*.*)
.
System.Windows.Forms.FileDialog.DefaultExt (MSDN):
When the user of your application specifies a file name without an extension, the FileDialog appends an extension to the file name. The extension that is used is determined by the Filter and DefaultExt properties. If a filter is selected in the FileDialog and the filter specifies an extension, then that extension is used. If the filter selected uses a wildcard in place of the extension, then the extension specified in the DefaultExt property is used.
Microsoft.Win32.FileDialog.DefaultExt (MSDN):
By default, the AddExtension property attempts to determine the extension to filter the displayed file list from the Filter property. If the extension cannot be determined from the Filter property, DefaultExt will be used instead.
来源:https://stackoverflow.com/questions/6104223/wpf-savefiledialog-defaultext-ignored