Thursday, October 13, 2011

Reading Keys from App.Config

I would like to share a small code snippet that is useful if you need to read entries from a configuration file, for example: App.config

Below are the entries I want to read from my App.config

<?xml version="1.0"?>
    <add key="MyServiceURL" value=""/>
<startup><supportedRuntime version="v2.0.50727"/></startup></configuration>

Below is the best way I've found so far to read these entries in C#:

//Scan Thru the keys and use the Configuration Manager to make this happen
foreach (string key in ConfigurationManager.AppSettings)
 //Get your key
 string value = ConfigurationManager.AppSettings[key];
 this.Url = value;

Keep in mind that you need to add a reference to the System.Manager assembly for this to work.
I've tested this with the .NET Framework 3.5 and 4.0


  1. The reference is System.Configuration

  2. Why would you need to iterate through the entire values in the config file when you know the exact one you need. This overhead is not needed