C# App.config 配置文件

C# App.config 配置

自定义app.config节点,读取以及修改

批量配置读取

环境配置

导入System.Configuration.dll
引用 using System.Configuration;

1.自定义节点目录

app.config是遵循xml格式的文件,所以支持自定义节点
但是自定义节点的文件格式需要按照目录来设定

  • 目录格式
<configuration>
  <configSections>
    <sectionGroup name="TestGroup" >
      <section name="Test" type="System.Configuration.NameValueSectionHandler"/>
      <section name="Test1" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
    <sectionGroup name="newGroup" >
      <section name="new" type="System.Configuration.NameValueSectionHandler"/>
      <section name="new1" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
  </configSections>
</configuration>

configSections节点要置于configuration内的第一个节点,否则报错配置系统未能初始化

  • 配置对应的sectionGroup,name属性是父节点标签名
  • 配置对应的section,name属性是sectionGroup下面子节点的标签名,type属性是System.Configuration.NameValueSectionHandler

2.自定义节点

根据配置好的自定义节点目录,配置自定义节点的格式

位置要置于configSections之后

  <TestGroup>
    <Test>
      <add key="Hello" value="World"/>
      <add key="Hello1" value="World1"/>
      <add key="Hello2" value="World2"/>
      <add key="Hello3" value="World3"/>
    </Test>
    <Test1>
      <add key="let's" value="go"/>
      <add key="let's1" value="go1"/>
      <add key="let's2" value="go2"/>
      <add key="let's3" value="go3"/>
    </Test1>
  </TestGroup>
 
  <newGroup>
    <new>
      <add key="happy" value="day"/>
      <add key="happy1" value="day1"/>
      <add key="happy2" value="day2"/>
      <add key="happy3" value="day3"/>
    </new>
    <new1>
      <add key="good" value="man"/>
      <add key="good1" value="man1"/>
      <add key="good2" value="man2"/>
      <add key="good3" value="man3"/>
    </new1>
  </newGroup>

3.读取自定义节点

//NameValueCollection是key/value字典类型的数据结构
NameValueCollection nc = (NameValueCollection)ConfigurationManager.GetSection("TestGroup/Test");

AppSetting配置

节点配置

appSettings放在configuration节点下面

<appSettings>
    <add key="connectionstring" value="sql conection string" />
    <add key="TemplatePATH" value="Template" />
</appSettings>

节点读取

//获取Config对象
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//根据key获取value
string name = config.AppSettings.Settings["connectionstring"].Value;
原文地址:https://www.cnblogs.com/tangpeng97/p/14473576.html