Runar Ovesen Hjerpbakk

Software Philosopher

Saving a configuration in C# using XDocument

The System.Configuration-namespace contains the classes for working with an applications configuration. Using the API, you can work with the configuration on a higher level than the XML it is represented by. This includes both editing and saving.

var ConfigurationFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "My.config" };
var config = ConfigurationManager.OpenMappedExeConfiguration(ConfigurationFileMap, ConfigurationUserLevel.None);
if (config != null)
{
    // do stuff
    config.Save();
}

The snippet above shows a trivial example of opening and saving a configuration. Configuration’s Save-method uses the XmlUtilWriter class internally. However, this will also format the XML according to its own rules with no options of customization. In my case, line-breaks where aggressively inserted and the resulting XML was ugly and far to narrow for my liking.

Being not too keen on doing the serialization manually, I remember that the XDocument formatting generally looks OK. My solution was to read and save the XML using XDocument immediately after saving the configuration:

var ConfigurationFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "My.config" };
var config = ConfigurationManager.OpenMappedExeConfiguration(ConfigurationFileMap, ConfigurationUserLevel.None);
if (config != null)
{
    // do stuff
    config.Save();
    
    // Format XML
    XDocument configXml = XDocument.Load(configuration.FilePath);
    configXml.Save(configuration.FilePath, SaveOptions.None);
}

Not the cleanest of solutions, but the resulting XML looks much better.