从App.Config文件中的configSections获取节名称

时间:2015-01-23 17:22:31

标签: c# .net

我想知道一种方法来获取App.Config文件中标记configSections内的所有部分名称。

到目前为止,我发现的是这样的:

var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var localSections = cfg.Sections.Cast<ConfigurationSection>().Where(s => s.SectionInformation.IsDeclared);

但由于某些原因,localSections似乎总是为空。 以下是我的app.config文件的样子:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
  <add key="frequency" value=""/>
</appSettings>
<configSections>
  <section name="Name1" type="System.Configuration.NameValueSectionHandler" />
  <section name="Name2" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<Name1>
  <add key="active" value="on"/>
  <add key="repeat" value="off"/>
</Name1>
<Name2>
  <add key="active" value="on"/>
  <add key="repeat" value="off"/>
</Name2>
</configuration>

1 个答案:

答案 0 :(得分:2)

您可以按章节信息

获取SectionName
string s;
var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var localSections = cfg .Sections.Cast<ConfigurationSection>().Where(s => s.SectionInformation.IsDeclared);
foreach( var i in localSections)
     s = i.SectionInformation.SectionName;