一:给 C# 类库 dll 添加配置文件并读取配置信息

效果:

 

 

 

1.给类库程序添加配置文件,并命名为:类库名.DLL.config

如上面效果图,类库为:API.dll ,那么其对应的类库配置文件为:API.DLL.config

注意:运行时config文件需跟类库dll在同一级目录下,不然读取不到文件

给配置文件添加相关的配置信息

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--Start 企业微信接口配置,默认不需要更改,企业微信属于私有化的请修改  Start-->
    <!--注意:链接必须是以'/'结尾-->
    <add key="Api" value="https://api.weixin.qq.com/" />
    <add key="QyApi" value="https://qyapi.weixin.qq.com/" />
    <add key="FileApi" value="http://file.api.weixin.qq.com/" />
    <add key="ApiMch" value="https://api.mch.weixin.qq.com/" />
   <!--END 企业微信接口配置   END-->
  </appSettings>
</configuration>
2.创建APIConfHelper.cs 类,为读取配置信息封装方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
namespace API.Helpers
{
    /// <summary>    
    /// 支持AppSettings和ConnectionStrings节点 ,如需其他节点请自行扩展
    /// </summary>    
    public class APIConfHelper
    {
        //实现 AppSettings 节点的读取          
        public static Hashtable AppSettings
        {
            get
            {
                return GetNameAndValue("appSettings", "key", "value");
            }
        }
        /// <summary>       
        /// 实现对AppSettings节点对应key的value设置        
        /// </summary>        
        /// <param name="keyNameValue"></param>        
        /// <param name="value"></param>     
        public static void SetAppSettings(string keyNameValue, string value)
        {
           
            SetNameAndValue("appSettings", "key", keyNameValue, value);
        }
        //实现 ConnectionStrings 节点的读取           
        public static Hashtable ConnectionStrings
        {
            get
            {
                return GetNameAndValue("connectionStrings", "name", "connectionString");
            }
        }
        /// <summary>        
        /// 实现对connectionStrings 节点对应name的value设置        
        /// </summary>        
        /// <param name="keyNameValue"></param>        
        /// <param name="value"></param>        
        public static void SetConnectionStrings(string keyNameValue, string value)
        {
            SetNameAndValue("connectionStrings", "name", keyNameValue, value);
        }
        /// <summary>
        /// 实现对相应节点的对应节点对应key或者name对应value值的设置        
        /// </summary>        
        /// <param name="sectionTag">对应节点</param>        
        /// <param name="KeyOrName">对应key或者name</param>        
        /// <param name="keyNameValue">key或者name的值</param>        
        /// <param name="valueOrConnectionString">对应key或者name 的value值</param>        
        private static void SetNameAndValue(string sectionTag, string KeyOrName, string keyNameValue, string valueOrConnectionString)
        {
            string assemblyPath = Assembly.GetExecutingAssembly().GetName().CodeBase;
            //获取运行项目当然DLL的路径            
            assemblyPath = assemblyPath.Remove(0, 8);
            //去除路径前缀            
            string configUrl = assemblyPath + ".config";
            //添加.config后缀,得到配置文件路径           
            try
            {
                XmlDocument cfgDoc = new XmlDocument();
                cfgDoc.Load(configUrl);
                XmlNodeList nodes = cfgDoc.GetElementsByTagName(sectionTag);
                foreach (XmlNode node in nodes)
                {
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        XmlAttributeCollection attributes = childNode.Attributes;
                        if (attributes!=null)
                        {
                            if (attributes.GetNamedItem(KeyOrName).InnerText == keyNameValue)
                            {
                                attributes.GetNamedItem("value").InnerText = valueOrConnectionString;
                            }
                        }
                    }
                }
                cfgDoc.Save(configUrl);
            }
            catch (FileNotFoundException es)
            {
                throw es;
            }
        }
        /// <summary>
        /// 根据节点名,子节点名,获取指定值           
        /// </summary>           
        /// <param name="sectionTag">对应节点</param>           
        /// <param name="KeyOrName">key或者name</param>           
        /// <param name="valueOrConnectionString">key或者name的值</param>           
        /// <returns>key或者name对应value值</returns>           
        private static Hashtable GetNameAndValue(string sectionTag, string KeyOrName, string valueOrConnectionString)
        {
            Hashtable settings = new Hashtable(5);//初始化Hashtable             
            string assemblyPath = Assembly.GetExecutingAssembly().GetName().CodeBase;//获取运行项目当前DLL的路径            
            assemblyPath = assemblyPath.Remove(0, 8); //去除前缀            
            string configUrl = assemblyPath + ".config"; //添加 .config 后缀,得到配置文件路径                
            XmlDocument cfgDoc = new XmlDocument();
            FileStream fs = null;
            try
            {
                fs = new FileStream(configUrl, FileMode.Open, FileAccess.Read);
                cfgDoc.Load(new XmlTextReader(fs));
                XmlNodeList nodes = cfgDoc.GetElementsByTagName(sectionTag);
                foreach (XmlNode node in nodes)
                {
                    foreach (XmlNode childNode in node.ChildNodes)
                    {
                        XmlAttributeCollection attributes = childNode.Attributes;
                        if (attributes!=null)
                        {
//为null不添加 settings.Add(attributes[KeyOrName].Value, attributes[valueOrConnectionString].Value); } } } }
catch (FileNotFoundException es) { throw es; } finally { if (fs != null) { fs.Close(); } } return settings; } } }
3.调用方法读取节点配置信息
        /// <summary>
        /// 基础URL
        /// </summary>
        private static string baseUrl = APIConfHelper.AppSettings["Api"].ToString();

 

posted on 2020-09-16 10:26  JioNote  阅读(1830)  评论(0编辑  收藏  举报