C# 读取Config文件

880 阅读1分钟

读取配置文件的信息(包括使用节点appSettings和自定义节点)

配置文件

<?xml version="1.0" ?>
<configuration>
	<configSections>	
		<!--类型加dll名称,此处应该是利用反射-->
		<section name="zxt" type="HRP.WEBAPI.TEST.Model.HFilterConfig, HRP.WEBAPI.TEST" />
	</configSections>
	<zxt>
		<add key="aa" value="11111"></add>
		<add key="bb" value="22222"></add>
		<add key="cc" value="33333"></add>
	</zxt>
	<appSettings>
		<add key="aa" value="11111"></add>
		<add key="bb" value="22222"></add>
		<add key="cc" value="33333"></add>
	</appSettings>
</configuration>

读取appSettings中的数据

	[HttpGet, Route("/rxml")]
        public ResData<object> ReadXmlByAppSettings()
        {
            var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "HrpWeb.Config" };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");
            var result =appsection.Settings.AllKeys.ToDictionary(k => k, k => appsection.Settings[k].Value);          
            return new ResData<object> { Msg = "success", Code = ResCode.Success, Data = result };
        }

读取自定义节点的数据

创建读取自定义config的类

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

namespace HRP.WEBAPI.TEST.Model
{
    public class HFilterConfig : ConfigurationSection {//获取的节点需要进行转换
        private static readonly ConfigurationProperty s_property = 
            new ConfigurationProperty(string.Empty, typeof(TheKeyValueCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);

        [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public TheKeyValueCollection KeyValues=> (TheKeyValueCollection)base[s_property];
    }


    [ConfigurationCollection(typeof(TheKeyValue))]
    public class TheKeyValueCollection : ConfigurationElementCollection // 自定义一个集合
    {
        new public TheKeyValue this[string name] => (TheKeyValue)base.BaseGet(name);

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

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((TheKeyValue)element).Key;
        }
    }
    public class TheKeyValue : ConfigurationElement    // 集合中的每个元素
    {
        //此处是key,若是type可替换即可
        [ConfigurationProperty("key", IsRequired = true)]
        public string Key
        {
            get { return this["key"]?.ToString(); }
            set { this["key"] = value; }
        }
        [ConfigurationProperty("value", IsRequired = true)]
        public string Value
        {
            get { return this["value"]?.ToString(); }
            set { this["value"] = value; }
        }
    }

}

配置文件中添加节点

<configSections>	
		<!--类型加dll名称,此处应该是利用反射-->
		<section name="zxt" type="${类名}, ${该类生成的dll名称}" />
	</configSections>

读取自定义config文件

[HttpGet, Route("/ReadXmlByYouself")]
        public ResData<object> ReadXmlByYouself()
        {                       
            var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "HrpWeb.Config" };//配置文件路径
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var filterConfig = config.GetSection("zxt") as HFilterConfig;
            var values = from kv in filterConfig.KeyValues.Cast<TheKeyValue>()
                         select new
                         { key = kv.Key, val = kv.Value};
            
            return new ResData<object> { Msg="success",Code=ResCode.Success,Data= values };
        }