C#: Error occuring when I want to save a file via SaveFileDialog?

Viewed 211

I Have a little problem with my C# code.

In my method, I create a XDocument/XML-File and after that, I want to save it via SaveFileDialog. It works everything fine until I click the "Save"-Button in the Dialog and then an error appears, which says "The File C:\Users\User\Desktop\XMLOutput.xml is not existing. Check, if the correct file name was indicated."

So here is my code:

public void Create_XMLFile()
    {
        XDocument xDoc = new XDocument(
            new XElement("itemlist",
                new XElement("item",
                    new XAttribute("article", "1"),
                    new XAttribute("quantity", "200"),
                    new XAttribute("price", "35")))
        );

        SaveFileDialog saveFileDialog = new SaveFileDialog();
        saveFileDialog.InitialDirectory = "C:\\";
        saveFileDialog.CheckFileExists = true;
        saveFileDialog.CheckPathExists = true;
        saveFileDialog.DefaultExt = "xml";
        saveFileDialog.Filter = "XML (*.xml)|*.xml|All (*.*)|*.*";
        saveFileDialog.FilterIndex = 2;
        saveFileDialog.RestoreDirectory = true;
        saveFileDialog.FileName = "XMLOutput";

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {                
            xDoc.Save(saveFileDialog.FileName);
        }
    }

// Button, which triggers the method above
private void Export_Click(object sender, RoutedEventArgs e)
    {
        Create_XMLFile();
    }

So yeah, where is the problem in my code? I simply want to safe the XML-File in which path the user selected. But as I said, I always get this error message, after I Click the "Save"-Button in the Windows-Dialog. :(

Hope you guys can help me here.

1 Answers

You are setting saveFileDialog.CheckFileExists = true; This makes the dialog to show exactly this warning if the file does not exist yet. You would normally set this to true for Open dialogs, not for Save Dialogs. saveFileDialog.OverwritePrompt on the other hand, is usually set to true on save.

Related