读取app.config配置的相关问题

本文介绍了如何在App.config文件中正确配置自定义设置,包括configSections节点的位置要求、自定义配置声明的方法以及具体的代码实现示例。
最近用到需要在App.config 文件中配置相关内容的代码,遇到过一些问题,总结了一下:

首先如果配置文件中有 configSections 节点,该节点必须放在第一位否则会出现各种问题。
自定义的配置必须在 configSections 节点中进行声明,否则读取相关Section信息的时候返回值为null。
如下给出一段在 App.config 文件中自定义配置的代码:

App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="loginUrl" value="~/RedirectValue.cshtml" />
    <add key="autoFormsAuthentication" value="false"/>
  </appSettings>
  <configSections>
    <!-- Servcies Defination -->
    <section name="services" type="ServciesHost.ServicesConfig, ServciesHost"/>
  </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
    </startup>
  <services>
    <confs>
      <service id="0001" name="TestService1" path="TestService1.exe" description="TestService1"/>
      <service id="0002" name="TestService2" path="TestService2.exe" description="TestService2"/>
    </confs>
  </services>
</configuration>

ServiceElement.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace ServciesHost
{
    public class ServiceElement:ConfigurationElement
    {
        [ConfigurationProperty("id")]
        public string Id
        {
            get { return (string)this["id"]; }
            set { this["id"] = value; }
        }

        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("path")]
        public string Path
        {
            get { return (string)this["path"]; }
            set { this["path"] = value; }
        }

        [ConfigurationProperty("description")]
        public string Description
        {
            get { return (string)this["description"]; }
            set { this["description"] = value; }
        }
    }
}

ServcieCollection.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace ServciesHost
{
    public class ServcieCollection:ConfigurationElementCollection
    {

        public ServiceElement this[int index]
        {
            get { return (ServiceElement)BaseGet(index); }
        }

        public new ServiceElement this[string id]
        {
            get { return (ServiceElement)BaseGet(id); }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new ServiceElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ServiceElement)element).Id;
        }
    }
}

ServicesConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Reflection;

namespace ServciesHost
{
    public class ServicesConfig:ConfigurationSection
    {
        private static ServicesConfig _servicesConfig = null;

        [ConfigurationProperty("confs", IsDefaultCollection = true)]
        [ConfigurationCollection(typeof(ServcieCollection), AddItemName = "service")]
        public ServcieCollection Services
        {
            get { return (ServcieCollection)this["confs"]; }
        }

        public static ServicesConfig CurrentConfig
        {
            get {
                return _servicesConfig;
            }
        }

        private static Configuration _config;

        public static ServicesConfig Initialize()
        {
            try
            {
                _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                _servicesConfig = _config.GetSection("services") as ServicesConfig;

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return _servicesConfig;
        }
    }

    public class NameValueSection : ConfigurationSection
    {
        [ConfigurationProperty("", IsDefaultCollection = true)]
        public NameValueConfigurationCollection Settings
        {
            get
            {
                return (NameValueConfigurationCollection)base[""];
            }
        }
    }
}

Program.cs

using CommonLibary;
using System.Configuration;
using System;

namespace ServciesHost
{
    class Program
    {
        static void Main(string[] args)
        {
            ServicesConfig.Initialize();
            Console.ReadLine();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值