Something I've found infinitely useful is custom configuration sections. By using custom configuration sections, you are allowed to store a richer amount of information in the application config file, than when you simply add values to the <appSettings> section.
To add a custom config section, you must do 2 things: 1) declare the section group and section in the <configSections> portion of the app.config file, and 2) add the new sections to the config file.
To create a new section group that holds Vehicles add this code to your config file:
<configSections>
<sectionGroup name="Vehicles">
<section name="Honda" type="System.Configuration.NameValueSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" />
<section name="Nissan" type="System.Configuration.NameValueSectionHandler,system, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=null" />
</sectionGroup>
</configSections>
This code declares a new section group called Vehicles, which holds the sections Honda and Nissan. It also declares that you will use the NameValueCollection object to get the information from the config file.
Next add the new configuration sections to your config file. These sections are added to the same level as the <configuration> element. Our new sections now look like this:
<Vehicles>
<Honda>
<add key="Accord" value="Black" />
<add key="Civic" value="Blue" />
</Honda>
<Nissan>
<add key="Altima" value="Tan" />
<add key="Pathfinder" value="Silver" />
</Vehicles>
Now that your config file has the appropriate values, you must write some code to get them out. To do this, use the NameValueCollection object from the System.Collections.Specialized namespace. This class is basically a HashTable object, with a couple more bells and whistles.
object o = ConfigurationSettings.GetConfig(“Vehicles/Honda);
Specialized.NameValueCollection col = o as Specialized.NameValueCollection;
if(o == null)
throw new ConfigurationException("Unable to load Honda section”);
Specialized.NameValueCollection.KeysCollection keys = col.Keys;
This code allows you to get all the keys for the NameValueCollection. You can then iterate over it using a for loop, extracting the values as you work your way through it.
for(int i=0;i<keys.Count;i++)
{
System.Console.WriteLine(col[i]);
}
[Currently Playing: Rage Against the Machine - Self-titled]