使用SaveFileDialog保存JSON文件时FileName始终为空,求排查
问题:SaveFileDialog.FileName始终为空的排查
我创建了带保存按钮的UI,用于将当前配置导出为JSON文件到指定位置。
按钮XAML代码:
<Button Height="25" Margin="5, 0, 0, 0" Width="50" Command="{Binding SaveConfigurationCommand}"> <Button.Content> <Border CornerRadius="5"> <TextBlock Text="Save" FontSize="10" Foreground="White"/> </Border> </Button.Content> </Button>
ViewModel代码:
private DelegateCommand saveConfigurationCommand; public DelegateCommand SaveConfigurationCommand => saveConfigurationCommand ?? (saveConfigurationCommand = new DelegateCommand(ExecuteSaveConfigurationCommand)); void ExecuteSaveConfigurationCommand() { try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "json files (*.json)|"; saveFileDialog.InitialDirectory = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\Configuration")); if (saveFileDialog.ShowDialog() == true) { Configuration configuration = new Configuration { Weight = total_weight, Animals = new List<Container>(animals), Items = new List<Item>(Items) }; File.WriteAllText(saveFileDialog.FileName, Newtonsoft.Json.JsonConvert.SerializeObject(configuration)); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Save configuration error", MessageBoxButton.OK, MessageBoxImage.Error); } }
当前遇到的问题:saveFileDialog.FileName始终为空,请问哪里操作有误?
解决方案
问题出在SaveFileDialog.Filter的格式设置错误:
- 你当前的Filter值是
"json files (*.json)|",不符合正确的格式要求。Filter的标准格式应为"显示名称(*.扩展名)|*.扩展名",管道符|前后需要对应文件类型的描述和实际的扩展名匹配规则。
修改后的Filter代码:
saveFileDialog.Filter = "json files (*.json)|*.json";
补充说明
- 错误的Filter会导致对话框无法正确识别可保存的文件类型,用户即使点击保存,对话框也可能无法生成有效的FileName。
- 另外可以检查
InitialDirectory对应的路径是否存在,如果路径不存在,SaveFileDialog会自动跳转到默认路径,但这不会直接导致FileName为空,不过建议提前确保该目录存在,避免用户困惑。
内容的提问来源于stack exchange,提问作者galex
相关产品推荐
相关产品推荐

