3

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.

  • wouldn't it be more beneficial to store settings which change in a database? as changes to the web config force a rebuild in iis – P6345uk Aug 05 '15 at 17:56
  • Normally it would, yes. What I'm experimenting with here is if I can load an app.config, modify it, and then re-save it under a different name; essentially creating 'profiles' for that configuration. For example there would be: myapp.exe.config as well as myapp.user1.config, myapp.user2.config, etc... – mvastarelli Aug 06 '15 at 15:50
  • but if you did that they wouldn't be available until the web.config loaded. is this intended functionality? – P6345uk Aug 07 '15 at 15:42
  • This is intended. It's an experimental design I'm trying, but essentially what I want to do is launch the app, and then depending on what "profile" is given on the command line it would load that specific app.config and use it to drive the app. – mvastarelli Aug 07 '15 at 17:08

1 Answers1

1

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();
Ross Bush
  • 14,648
  • 2
  • 32
  • 55