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"?>
<configuration>
 <appSettings>
    <add key="MyServiceURL" value="http://10.12.64.190:8086/MyService"/>
  </appSettings>
<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
HTH,
Will




3 comments:

  1. The reference is System.Configuration

    ReplyDelete
  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

    ReplyDelete