Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

c# - empty path name not legal

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...