February 06, 2008

Configuration namespace and reading settings from the Configuration file,app.config,web.config

This one always catches me out.
There are a few different ways to read settings in from a .config file.
The confusion for me occurs when reading from certain sections and from config files other than ones for the currently running application.

The easiest example is reading settings from the currently running application, from within it's own code.
You can access the AppSettings Section
<add key="hostname1" value="localhost"/><add key="hostname2" value="othername"/></appSettings></configuration>

NameValueCollection appSettings = ConfigurationManager.AppSettings;
foreach(string key in appSettings.AllKeys)
Console.WriteLine(key + " " + appSettings[key]);

So now you've all the keys in the AppSettings section i.e. "hostname1" and "hostname" and all their values accessed with appSettings[key].
Note: First you must add a reference to 'System.Configuration.dll' to your project and also include the namespace 'using System.Configuration;' You'll also need 'using System.Collections.Specialized;' in order to use the 'NameValueCollection' type.

Similarly but slightly more tricky you can access the settings of another assembly by using the following:

Configuration config = ConfigurationManager.OpenExeConfiguration(@".dll");
KeyValueConfigurationCollection kvpCollection = config.AppSettings.Settings;
foreach (string key in kvpCollection.AllKeys)
Console.WriteLine(key + " " + kvpCollection[key].Value);

You'll see the Settings collection is access in the same way and can be enumerated in the same way but the 'value' of the AppSetting must be accessed using the .Value property?
This is because the former call to AllKeys returns a NamedValueCollection and the latter returns a KeyValueCollection, this means that for one you have access to the values as strings themselves and the other you have access to the type KeyValueConfigurationElement, if you want to get the string value you additionally need to call the Value property!

Open a config for a dll, a dll being referenced by an exe

This reads the config file that's in the location that the exe is referencing the dll from, actually it makes a copy of the dll to the exes bin dir, so you have to add your dll's config file to the exe's bin directory and withing the dll's code add the following

//Only finds copy of the assembly as it's added as a reference to the exe.
System.Reflection.Assembly ass = System.Reflection.Assembly.GetAssembly(typeof(Class1));
System.Reflection.AssemblyName assName = ass.GetName();
string codeBase = assName.CodeBase;
int length = "file:///".Length;//remove the "file:///" from the string
string result = codeBase.Substring(length);
config = ConfigurationManager.OpenExeConfiguration(result);//open the dll's config
kvpCollection = config.AppSettings.Settings;
value = kvpCollection["hostname1"].Value;

No comments: