Empty way

I have a Save button, so when users click, it will save the xml file (xml serialization). Savefiledialog is used here, and when I click cancel without selecting any files, an “Exception Argument” occurs and says: “An empty path is not legal”. How can I handle this exception? I would like the form to remain the same even without any path selected in the savefiledialog file. Thank you very much.

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

An exception to my argument occurs on this line:

 using (Stream savestream = new FileStream(savepath, FileMode.Create)) { XmlSerializer serializer = new XmlSerializer(typeof(FormSaving)); serializer.Serialize(savestream, formsaving); } 
+4
source share
2 answers

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

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

You probably don't want to save if the user cancels the dialog? Check 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); } } 
+4
source

Source: https://habr.com/ru/post/1341609/


All Articles