Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 554
jeremychan Avatar asked Jan 20 '23 09:01

jeremychan


1 Answers

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();
like image 56
Øyvind Bråthen Avatar answered Jan 28 '23 22:01

Øyvind Bråthen