我想要一个小的可执行文件具有一个app.config文件与多个部分位于section“组件”applicationSettings“(不是”appSettings“,我不需要写入该文件).每个部分将具有与设置时应加载的模块相对应的名称.
这里有一个例子:
<configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup,System,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" > <section name="Executable" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="FirstModule" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup> </configSections> <applicationSettings> <Executable> <setting name="MyFirstSetting" serializeAs="String"> <value>My awesome feature setting</value> </setting> </Executable> <FirstModule path="path to the modules assembly"> <setting name="ImportantSettingToTheModule" serializeAs="String"> <value>Some important string</value> </setting> </FirstModule> </applicationSettings> </configuration>
现在如果我定义了FirstModule部分,我希望我的应用程序加载它的程序集.如果未定义该部分,则不应加载该模块.这不仅仅是一个模块,而是一个尚未定义的模块.
所以我基本上需要在运行时了解定义的部分.我该怎么做?
此外,我希望这可以成为一个可移植的可执行文件(=它必须运行在Mono),这是向后兼容的.NET 2.0.
看看GitHub的项目可能会很有趣(目前在this commit).
解决方法
ConfigurationManager.OpenExeConfiguration
功能加载在您的配置文件.
然后在System.Configuration.Configuration
类上,您将从ConfigurationManager.OpenExeConfiguration返回,您将要查看SectionGroups属性.这将返回一个ConfigurationSectionGroupCollection
,您将在其中找到applicationSettings部分.
在ConfigurationSectionGroupCollection中将有一个Sections属性,其中包含可执行文件和FirstModule ConfigurationSection
对象.
var config = ConfigurationManager.OpenExeConfiguration(pathToExecutable); var applicationSettingSectionGroup = config.SectionGroups["applicationSettings"]; var executableSection = applicationSettingSectionGroup.Sections["Executable"]; var firstModuleSection = applicationSettingSectionGroup.Sections["FirstModule"];
在获取ConfigurationSectionGroupCollection对象或ConfigurationSection对象后,您将需要检查null.如果它们为空,则它们不存在于配置文件中.
您还可以使用ConfigurationManager.GetSection
获取部分
var executableSection = (ClientSettingsSection)ConfigurationManager .GetSection("applicationSettings/Executable"); var firstModuleSection = (ClientSettingsSection)ConfigurationManager .GetSection("applicationSettings/FirstModule");
再次,如果对象为空,则它们不存在于配置文件中.
var config = ConfigurationManager.OpenExeConfiguration(pathToExecutable); var names = new List<string>(); foreach (ConfigurationSectionGroup csg in config.SectionGroups) names.AddRange(GetNames(csg)); foreach (ConfigurationSection cs in config.Sections) names.Add(cs.SectionInformation.SectionName); private static List<string> GetNames(ConfigurationSectionGroup configSectionGroup) { var names = new List<string>(); foreach (ConfigurationSectionGroup csg in configSectionGroup.SectionGroups) names.AddRange(GetNames(csg)); foreach(ConfigurationSection cs in configSectionGroup.Sections) names.Add(configSectionGroup.SectionGroupName + "/" + cs.SectionInformation.SectionName); return names; }