Get Section Names Programmatically from App.config C#
有没有一种方法可以通过执行循环而不是自己硬编码来以编程方式获取节名称?
例如:
1 2 3 4 5 | <configuration> <configSections> <section name="Test1" type="System.Configuration.NameValueSectionHandler"/> <section name="Test2" type="System.Configuration.NameValueSectionHandler"/> </configSections> |
Hardcoding:
1 2 | var section = ConfigurationManager.GetSection("Test1") as NameValueCollection; var section = ConfigurationManager.GetSection("Test2") as NameValueCollection; |
我不想在代码中硬编码test1和test2部分名称。
您可以这样获得分区组名称:
1 2 3 4 5 6 7 8 9 10 11 | static void Main(string[] args) { string configPath = @"..\..\App.config"; var map = new ExeConfigurationFileMap(); map.ExeConfigFilename = configPath; var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); for (int i = 0; i < config.SectionGroups.Count; i++) { Console.WriteLine(config.SectionGroups[i].SectionGroupName); } } |