I have a dll that I want to read from a manually specified app.config file (the dll is an .net extension to a native com dll that is a Microsoft Management Console snap in, so there is no mmc.exe.config). I have been able to open the config file, read the relevant group and section to get the setting that I want. Like this:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Assembly.GetExecutingAssembly().Location + '.config'; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); ShowSectionGroupCollectionInfo(config.SectionGroups); ConfigurationSectionGroup group = config.SectionGroups['applicationSettings']; ClientSettingsSection section = group.Sections['Namespace.Properties.Settings'] as ClientSettingsSection; SettingElement sectionElement = section.Settings.Get('AllowedPlugins'); SettingValueElement elementValue = sectionElement.Value;
The settings are a string collection and a string. like so:
<applicationSettings> <Namespace.Properties.Settings> <setting name='AllowedPlugins' serializeAs='Xml'> <value> <ArrayOfString xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <string>Plugin1.Name</string> <string>Plugin2.Name</string> <string>Plugin3.Name</string> </ArrayOfString> </value> </setting> <setting name='blah' serializeAs='String'> <value>sajksjaksj</value> </setting> </Namespace.Properties.Settings> </applicationSettings>
I can create a string array from this in a bit of a kak handed way:
List<String> values = new List<string>(elementValue.ValueXml.InnerText.Split(new string[]{' ',Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries ));
but I wonder if there is a nice way that I’m missing that I can get my settings to be read and converted into objects of the right type in the same way that they are when the standard app.config file is read.
Please tell me there is…
The way that I’ve done this in the past is use a custom configuration section and implement an
IConfigurationSectionHandlerfor the section. You still have to do all of the parsing inside the configuration section handler, but it makes it easy to get the information in the configuration section in the form you want it in your application. There is a How To article on MSDN that goes through the process of creating such a handler.Below is an example of one that I’ve used:
usage:
web.config:
code: