How do you use sections in c# 4.0 app.config?
我想使用我的app config来存储两个公司的设置,如果可以使用一个部分将一个公司的数据与另一个公司的数据分开,而不是给出不同的密钥名,我更愿意这样做。
我一直在网上查看,但当人们使用分区或找到过时的简单方法使用分区时,我似乎有点不知所措。有人能给我一个入门指南吗?
下面是我的app.config的示例:
1 2 3 4 5 6 7 8 9 10 11 | <configSections> <section name="FBI" type="" /> <section name="FSCS" type="" /> </configSections> <FSCS> </FSCS> <FBI> </FBI> |
更新:
基于Anwer的高级解决方案。以防有人想知道。
App.config:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <configuration> <configSections> <sectionGroup name="FileCheckerConfigGroup"> <section name="FBI" type="System.Configuration.NameValueSectionHandler" /> <section name="FSCS" type="System.Configuration.NameValueSectionHandler" /> </sectionGroup> </configSections> <FileCheckerConfigGroup> <FSCS> </FSCS> <FBI> </FBI> </FileCheckerConfigGroup> </configuration> |
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Get the application configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Get the collection of the section groups. ConfigurationSectionGroupCollection sectionGroups = config.SectionGroups; foreach (ConfigurationSectionGroup sectionGroup in sectionGroups) { if (sectionGroup.Name =="FileCheckerConfigGroup") { foreach (ConfigurationSection configurationSection in sectionGroup.Sections) { var section = ConfigurationManager.GetSection(configurationSection.SectionInformation.SectionName) as NameValueCollection; inputDirectory = section["inputDirectory"]; //"C:\\testfiles"; } } } |
1 2 3 4 5 6 7 8 9 10 11 | <configSections> <section name="FBI" type="System.Configuration.NameValueSectionHandler" /> <section name="FSCS" type="System.Configuration.NameValueSectionHandler" /> </configSections> <FSCS> </FSCS> <FBI> </FBI> |
然后:
1 2 | var section = ConfigurationManager.GetSection("FSCS") as NameValueCollection; var value = section["processingDirectory"]; |
App.CONFIG
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <configSections> <sectionGroup name="FileCheckers"> <section name="FBI" type="System.Configuration.NameValueSectionHandler" /> <section name="FSCS" type="System.Configuration.NameValueSectionHandler" /> </sectionGroup> </configSections> <FileCheckers> <FSCS> </FSCS> <FBI> </FBI> </FileCheckers> |
示例用法
1 2 3 4 5 6 7 | Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSectionGroup fileCheckersGroup = config.SectionGroups["FileCheckers"]; foreach (ConfigurationSection section in fileCheckersGroup.Sections) { NameValueCollection sectionSettings = ConfigurationManager.GetSection(section.SectionInformation.SectionName) as NameValueCollection; var value = sectionSettings["processingDirectory"] } |