When key value pairs are not enough I use Configuration Sections as they are not complex to use (unless you need a complex section):
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()
{
}
}
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
// in the <configSections> and the
// related target section in <configuration>.
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:
<?xml version="1.0" encoding="utf-8" ?>
<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" />
</configSections>
<CustomSection LastName="TEST" FirstName="TEST" />
</configuration>
Now Retrieve your section properties:
CustomSection section = (CustomSection)ConfigurationManager.GetSection("CustomSection");
string lastName = section.LastName;
string firstName = section.FirstName;