我有一个“保存”按钮,所以当用户点击时,它会保存xml文件(xml序列化)。这里使用了savefiledialog,当我按下取消而不选择任何文件时出现“参数异常”并说“空路径名称不合法”。我该如何处理这个例外?即使没有在savefiledialog中选择任何路径,我希望表单保持不变。非常感谢。
我的savefiledialog片段:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = @"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
...
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
}
我的参数异常发生在这一行:
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
答案 0 :(得分:5)
这里的问题是您不关心“保存”对话框的结果,即使用户单击“取消”,您也会尝试保存。你应该改变代码看起来像这样:
...
DialogSave.InitialDirectory = @"C:/";
if( DialogSave.ShowDialog() == DialogResult.OK )
{
savepath = DialogSave.FileName;
DialogSave = null;
...
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
}
DialogSave.Dispose();
答案 1 :(得分:4)
如果用户取消对话框,您可能不想保存?检查ShowDialog
的结果并采取相应措施:
if (DialogSave.ShowDialog() == true)
{
savepath = DialogSave.FileName;
...
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, formsaving);
}
}