If you have created a custom section like this, and if you want to add it programmatically to web.config then you have to:

  1. Use the WebConfigurationManager class and open the web

Configuration config = WebConfigurationManager.OpenWebConfiguration(path, site);

From MSDN

path

The virtual path to the configuration file.

site

The name of the application Web site, as displayed in IIS configuration.

 

  1. Create a ConfigurationSectionGroup and add it to the Configuration object

ConfigurationSectionGroup sectionGroup = new ConfigurationSectionGroup();

config.SectionGroups.Add(“GROUP_NAME”, sectionGroup);

 

  1. Create a new instance of your section (MyCustomSection) and add it to the section group

MyCustomSection section = new MyCustomSection ();

sectionGroup.Sections.Add(“SECTION_NAME”, section);

 

  1. Fill your custom section properties

section.Property1 = “0123456789”;

section.Property2 = “Lorem ipsum dolor sit amet”;

 

  1. And save the configuration

config.Save();

If you take a look at your web.config you will see that it was modified programmatically as you specified. I use this technique in the setup process of sites. Cool!

LEAVE A REPLY

Please enter your comment!
Please enter your name here