C#如何自定义和加载App.config

我们一般创建的应用程序项目系统都会为它分配一个配置文件(应用程序项目一般为App.config)

默认内容如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>

有时候我们需要在项目里面去读取配置文件的相关内容,这里就要使用到了

System.Configuration.dll

System.Configuration.ConfigurationManager类为我们提供了AppSettings和ConnectionStrings属性,可以让我们方便的读取到对应Section里面的内容

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="Demo" connectionString="Data Source=xxx,xxx;database=xxx;User Id=xx;Password=xx;Max Pool Size=xx;Connect Timeout=5;" />
  </connectionStrings>
  <appSettings>
    <add key="ServiceName" value="xx" />
    <add key="ServiceDescription" value="xx" />
  </appSettings>
<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>

如我们需要读取appSetting里面的ServiceName 可以调用

ConfigurationManager.AppSettings.Get("ServiceName")

如何获取自定义内容呢

1、App.config中加入自定义Section

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="MySection" type="TestDemo.ConfigSectionHandler, TestDemo" />
  </configSections>
  <MySection>
    <A>
      <B name="1"></B>
    </A>
  </MySection>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
</configuration>

2、自定义ConfigSectionHandler类,实现System.Configuration.IConfigurationSectionHandler接口

namespace TestDemo
{
    class ConfigSectionHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            return section;
        }
    }
}

注意命名空间类名和App.config中type需要一致

3、主程序调用

static void Main(string[] args)
        {
            var obj = (System.Xml.XmlElement)System.Configuration.ConfigurationManager.GetSection("MySection");
            Console.WriteLine(obj["A"]["B"].GetAttribute("name"));
            System.Configuration.ConfigurationManager.RefreshSection("Mysection");
        }
THE END


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值