Thursday, October 2, 2008

[.NET] How to Programmatically Create and Access Custom ConfigurationSections

.NET app.config and web.config are powerful instruments to store simple key value pairs and connections strings.When you need to store config data in some specific format and key value pairs are not enough you can use Custom Configuration Sections as they are not complex to use (unless you need a fairly complex section):

1) Define your custom section:

public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("LastName", IsRequired = true,DefaultValue = "TEST")]
public String LastName
{
get { return (String)base["LastName"]; }
set { base["LastName"] = value; }
}

[ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")]
public String FirstName
{
get { return (String)base["FirstName"]; }
set { base["FirstName"] = value; }
}

public CustomSection()
{

}
}



2) Programmatically create your section (if it doesn't already exist):

// Create a custom section.
static void CreateSection()
{
try
{

CustomSection customSection;
// Get the current configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe");

// Create the section entry
// and the
// related target section
if (config.Sections["CustomSection"] == null)
{
customSection = new CustomSection();
config.Sections.Add("CustomSection", customSection);
customSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
}
catch (ConfigurationErrorsException err)
{
//manage exception - give feedback or whatever
}

}



Following CustomSection definition and actual CustomSection will be created for you:

<configuration>
<configsections>
<section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowlocation="true" allowdefinition="Everywhere" allowexedefinition="MachineToApplication" overridemodedefault="Allow" restartonexternalchanges="true" requirepermission="true">
</section>
</configsections>
<customsection lastname="TEST" firstname="TEST">
</customsection>
</configuration>


3) Now Retrieve your section properties:

CustomSection section=(CustomSection)ConfigurationManager.GetSection("CustomSection");
string lastName = section.LastName;
string firstName = section.FirstName;


This is all good stuff - nice and easy as you can see.

P.S. This post orginally appeared on this  StackOverflow link, but since I wrote it I thought it would do no harm to recycle my own rubbish here.


kick it on DotNetKicks.com

2 comments:

Anonymous said...

Nice, you can also see a video of this in action at

http://www.dimecasts.net/Casts/CastDetails/43

Anonymous said...
This comment has been removed by a blog administrator.