c# – 如何通过名称在.Net 2.0中的GroupGroup applicationSettin
这是我的想法:
我想要一个小的可执行文件具有一个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 功能加载在您的配置文件.
然后在 在ConfigurationSectionGroupCollection中将有一个Sections属性,其中包含可执行文件和FirstModule var config = ConfigurationManager.OpenExeConfiguration(pathToExecutable); var applicationSettingSectionGroup = config.SectionGroups["applicationSettings"]; var executableSection = applicationSettingSectionGroup.Sections["Executable"]; var firstModuleSection = applicationSettingSectionGroup.Sections["FirstModule"]; 在获取ConfigurationSectionGroupCollection对象或ConfigurationSection对象后,您将需要检查null.如果它们为空,则它们不存在于配置文件中. 您还可以使用 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |