Custom configuration section for .DLL

StuartProgramming Blog

The configurationManager class provided in Visual Studio 2008 has made working with complicated custom configuration file layouts. Recently I needed to create a configuration file for a particular .DLL that could be included like a plug-in to another application whose code I could not control. A few special considerations when using .config files in this way.

An application named application1.exe will always look for a configuration file named application1.exe.config. This won't work for our .DLL model, so the .DLL needs to know how to load its own .config.file.

//Make sure to include the System Configuration reference
using System.Configuration;
private static Configuration dllConfigurationManager;
private static customConfigurationSection cConfigSection;

//Create a mapping for this DLL's configuration file by first extracting the name of the .DLL from Assembly.GetExecutingAssembly().Location and then append a .config
ExeConfigurationFileMap fileMapping = new ExeConfigurationFileMap();
fileMapping.ExeConfigFilename = Assembly.GetExecutingAssembly().Location.ToString() + ".config";

//Create an instance of the Configuration Manager to handle this DLL's configuration using the fileMapping object created above
dllConfigurationManager = ConfigurationManager.OpenMappedExeConfiguration(fileMapping, ConfigurationUserLevel.None);

//Map the customConfigurationSection from this DLL's configuration file to the custom section
cConfigSection = (customConfigurationSection)dllConfigurationManager.GetSection("customConfigurationSection");

For more information on Custom Configuration sections in .NET check out:

http://www.4guysfromrolla.com/articles/032807-1.aspx

http://support.microsoft.com/kb/309045

http://www.codeproject.com/Articles/37776/Writing-a-complex-custom-configuration-section.aspx

And the following is an excellent graphical designer for custom sections that lets you add a “ConfigurationSection Designer” item to your Visual Studio project, then drag and drop configuration elements, groups, items and properties. It will then generate a sample config file and the .XSD that assists you and your future users create your own .config.

http://www.codeplex.com/csd

Tags: 

StuartCustom configuration section for .DLL