empty path name not legal

我是研究僧i 提交于 2019-11-28 08:36:10

问题


I have a "save" button so when users click, it will do a saving of xml file(xml serialization). A savefiledialog is used here and when i press cancel without selecting any file an "Argument Exception" occurs and says "Empty path name is not legal". How do i handle this exception? I would like the form to remain the same even without any path selected in the savefiledialog. Many thanks.

My savefiledialog snippet:

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

}

My argument exception occurs at this line:

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

回答1:


The problem here is that you do not care about the result of the Save dialog, and you try to save even if the user clicked Cancel. You should change the code to look something like this instead:

...
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();



回答2:


You probably don't want to save if the user cancels the dialog? Check for the result from ShowDialog and act accordingly:

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


来源:https://stackoverflow.com/questions/5139643/empty-path-name-not-legal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!