I have been working with the new custom configuration classes in .NET 2.0 and they really make creating custom xml configuration a snap. They are a little quirky to use at first but once you get past the initial learning curve they really make the job a lot easier.
One thing I really wanted to figure out is how to use these new classes to read files other than the default app/web.config. For example if you have one config file that might be shared between exes or if a config file is pulled from a URL. Its actually pretty easy to do.
First create your custom configuration file. It will look exactly the same as a web/app.config file except it will only contain your custom section(s). Create a section handler element identifying the custom section handler and the name of the section. Again, nothing different from doing this in the app/web.config.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="mySettings" type="CustomConfigHandler.MySettingSection, CustomConfigHandler"/>
</configSections>
<mySettings>
<someSetting someAttribute="This is an attribute value from Settings1.config"/>
</mySettings>
</configuration>
Next create a Configuration object that points to your file by passing in an ExeConfigurationFileMap with the ExeConfigFilename set.
// Create an exe file map containing the path to your config file
ExeConfigurationFileMap FileMap = new ExeConfigurationFileMap();
FileMap.ExeConfigFilename = "MySystem.config";
// Create a configuration object that is tied to your custom config file.
Configuration Config = ConfigurationManager.OpenMappedExeConfiguration(FileMap, ConfigurationUserLevel.None);
// Create the custom config section handler
MySettingSection MySettings = (MySettingSection)Config.GetSection("mySettings");
Console.WriteLine(MySettings.SomeSetting.SomeAttribute);
The entire source can be downloaded here:
ExternalConfigFile.zip (40.24 KB)