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




No comments:

Post a Comment