关于 c#:empty path name not legal

empty path name not legal

我有一个"保存"按钮,所以当用户点击时,它会保存 xml 文件(xml 序列化)。此处使用了保存文件对话框,当我在未选择任何文件的情况下按取消时,会出现"参数异常"并显示"空路径名不合法"。我该如何处理这个异常?即使在保存文件对话框中没有选择任何路径,我也希望表单保持不变。非常感谢。

我的存档对话框片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
        }

}

我的参数异常发生在这一行:

1
2
3
4
5
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
        XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
        serializer.Serialize(savestream, formsaving);
}

这里的问题是您不关心"保存"对话框的结果,即使用户单击了"取消",您也会尝试保存。您应该将代码更改为如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
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();


如果用户取消对话框,您可能不想保存?检查 ShowDialog 的结果并采取相应措施:

1
2
3
4
5
6
7
8
9
10
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);
    }
}