C# – Writing XML with C#

c++file-ioxml

My C# is a bit rusty and I've never written XML with it before. I'm having trouble getting the XML to write to a file if I attempt to write anything other than elements. Here is the test code that I have:

var guiPath = txtGuiPath.Text;
MessageBox.Show("Dumping File: " + guiPath);

try
{
    var writer = new XmlTextWriter("client_settings.xml", null);
    writer.WriteStartDocument();
    writer.WriteComment("Config generated on 01/01/01");
    writer.WriteStartElement("Config");
    writer.WriteStartElement("GuiPath");
    writer.WriteString(guiPath);
    writer.WriteEndElement();
    writer.WriteEndElement();
    writer.WriteEndDocument();
    writer.Close();
} catch (Exception ex) {
    MessageBox.Show(ex.Message);
}
MessageBox.Show("Finished Dumping");

If guiPath is blank I get the following XML:

<?xml version="1.0"?>
<!--Config generated on 01/01/01-->
<Config>
    <GuiPath />
</Config>

but if there is any text inside guiPath then nothing gets written to the file. I can even delete the client_settings.xml file and fire this code off over and over and the XML file never gets generated unless guiPath is empty. Passing something like "This is a test" to WriteString() works as well.

Update

Since I'm trying to write out a system path, that seems to be the problem. If I strip out all the backslashes it will write the resulting string correctly, but if I pass it to WriteString or WriteCData the XML will not write at all.

Update 2

Turns out that the reason I was having so many problems is because the XML file was being generated in whatever path guiPath was set to, not into the directory that the app was running from (so to me it looked like it wasn't being generated at all). So, if I had guiPath set to 'C:\Program Files\externalApp\appName.exe', it was saving the XML file as 'C:\ProgramFiles\externalApp\client_settings.xml' instead of in the startup folder for the app. Why, I don't know. I started passing Application.StartupPath and appended the filename to that and it works great now.

Thanks for all the help!

Best Solution

You might want to examine the API in System.Xml.Linq. It's a bit of a more flexible approach to generating and writing XML. Writing your document might go roughly like this:

XDocument document = new XDocument();
document.Add(new XComment("Config generated on 01/01/01"));
document.Add(new XElement("Config", new XElement("GuiPath", guiPath)));

// var xmlWriter = new XmlTextWriter("client_settings.xml", null);
// document.WriteTo(xmlWriter);

// thanks to Barry Kelly for pointing out XDocument.Save()
document.Save("client_settings.xml");