mvastarelli
mvastarelli

Reputation: 51

How do I save a configuration file with a custom configuration section?

I have an application that at run-time needs to insert a custom section into its app/web.config. Normally this can be accomplished with something like:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var mySection = new MyCustomSection { SomeProperty="foo" };

config.Sections.Add("mySection", mySection);
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);

The problem I'm running into here is that the section I'm adding to the configuration file needs its own serialization handler. I know this can easily be handled when reading the configuration by simply creating an implementation of IConfigurationSectionHandler, but I can't seem to find a way to actually write the configuration section itself.

Looking at the MSDN documentation the ConfigurationSection class does have a SerializeSection/DeserializeSection method, but they're marked internal and cannot be overridden. I also found a GetRawXml/SetRawXml method in SectionInformation, but they're marked as infrastructure-level calls that shouldn't be invoked directly by user code.

Is what I'm trying to do even possible? It seems like a pretty straight-forward use case.

Thanks.

Upvotes: 3

Views: 2132

Answers (1)

Ross Bush
Ross Bush

Reputation: 15175

Here is a method for saving on the System.Configuration.Configuration class.

System.Configuration.Configuration configRoot = null;
if(HttpContext.Current!=null)
    configRoot = WebConfigurationManager.OpenWebConfiguration(_urlRoot);
else
   configRoot = ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal);

ConfigurationSectionGroup configGroup = configRoot.GetSectionGroup("mySections");
foreach (ConfigurationSection configSection in configGroup.Sections)
{
    //Do some updating that needs to be saved.
}
configRoot.Save();

Upvotes: 1

Related Questions