This article describes how to read information from a config file exactly like the app.config file, including information on linking in external files, using custom configuration section handlers, sections, and section groups.
I have looked at several articles that build everything from preference sections to simply building something that reads a section from XML that looks like the
appSettings. What I really needed was a way to move settings into and out of the app.config file. I needed it to do two very specific things that none of the others did. First, I needed it to use custom configuration section handlers, and second, I needed it to assume the file name based on the assembly name because I didn't want to have to track the names of files.
Using the code
The code is used just like the
System.ConfigurationSettings class in .NET, just from a different namespace.
string val =
This is the simplest way to use it. Using it this way assumes a config file named assemblyname.dll.config or executable.exe.config, really it just picks up the output file name for the assembly and adds .config to it. The file should be in the same directory as the assembly. It supports all the built-in classes in .NET that support the
IConfigurationSectionHandler interface and uses them to read all sections of the config file. It also supports using external files for
appSettings just like the app.config does.
<add key="test" value="myTest"/>
If you don't want to use the
appSettings section, or you want to use a different file name then the one that is assumed, it works just like the
System.ConfigurationSettings class, except that the
ConfigurationSettings.GetConfig is overloaded to support passing a file name that can be whatever you want as long as the format of the file matches the app.config.
NameValueCollection values = (NameValueCollection)
string val = values["myTestKey"];
Points of Interest
Loading the external file for the
AppSettings looked like it was going to be easy, just use the
NameValueFileSectionHandler and that should do it, right? Well, not so fast! It didn't work. It was always returning
null. I looked at what it was doing internally using Reflector and it looked pretty simple, but it was using a class marked as
internal so I couldn't use that to reproduce the code. It wasn't that hard to just get the file name and load it myself, and then use the same logic that I was using on the first file, then set the parent context for the
NameValueSectionHandler which combines the two sets of information into the section handler.