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.
2 comments:
Nice, you can also see a video of this in action at
http://www.dimecasts.net/Casts/CastDetails/43
Post a Comment