C# 如何获取自定义的config中节点的值,并修改节点的值

现定义一个方法 DIYConfigHelper.cs

using System;
using System.Xml;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.IO;

namespace Chain.Common
{

    /// <summary>
    /// Summary description for ReadWriteConfig.
    /// </summary>
    public class DIYConfigHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">节点名称</param>
        /// <returns></returns>

        /// <summary>
        /// 获取自定义 index.config 文件中的 appsetting 节点值 
        /// flag -1:配置文件不存在 -2::节点不存在
        /// </summary>
        /// <param name="path">config文件的路径</param>
        /// <param name="key">节点名称</param>
        /// <returns>节点名称的值</returns>
        public static string GetIndexConfigValue(string path, string key)
        {
            string flag = "";
            string indexConfigPath = path;
            if (string.IsNullOrEmpty(indexConfigPath))
                return flag = "-1";//配置文件为空
            if (!File.Exists(indexConfigPath))
                return flag = "-1";//配置文件不存在

            ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
            ecf.ExeConfigFilename = indexConfigPath;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
            try
            {
                flag = config.AppSettings.Settings[key].Value;
            }
            catch (Exception)
            {
                flag = "-2";
            }
            return flag;
        }

        /// <summary>
        /// 设置自定义 index.config 文件中的 appsetting 节点值
        /// </summary>
        /// <param name="path">config文件的路径</param>
        /// <param name="key">节点名称</param>
        /// <param name="value">需要修改的值</param>
        /// <returns>true:修改成功 false:修改失败</returns>
        public static bool SetIndexConfigValue(string path, string key, string value)
        {
            string indexConfigPath = path;
            if (string.IsNullOrEmpty(indexConfigPath))
                throw new Exception("请检查应用程序配置文件 appSettings 节点,是否存在 indexConfig 且 value 不为空的配置节!");
            if (!File.Exists(indexConfigPath))
                throw new Exception(string.Format("配置文件不存在:{0}", indexConfigPath));

            ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
            ecf.ExeConfigFilename = indexConfigPath;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
            config.AppSettings.Settings[key].Value = value;
            config.Save();
            return true;
        }

        /// <summary>
        /// 给xlm指定的节点添加节点和值
        /// </summary>
        /// <param name="path">xml文件的路径</param>
        /// <param name="key">添加的key值</param>
        /// <param name="value">添加的value值</param>
        public static void AddIndexConfigValue(string path, string key, string value)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(path); //加载xml文件
            XmlNode rootXml = xmlDoc.SelectSingleNode("configuration"); //查询XML文件的根节点("siteMapPath")
            XmlNodeList xnl = rootXml.SelectNodes("appSettings"); //获取所有节点为"siteMapNode"的节点
            foreach (XmlNode xnItem in xnl)
            {
                XmlElement xe = (XmlElement)xnItem; //将子节点类型转换为XmlElement类型
                XmlElement newXE = xmlDoc.CreateElement("add");
                newXE.SetAttribute("key", key);
                newXE.SetAttribute(@"value", value);
                xnItem.AppendChild(newXE);
            }
            xmlDoc.Save(path);
        }
        /// <summary>
        /// 按xml路径删除指定节点
        /// </summary>
        /// <param name="path">xml文件路径</param>
        /// <param name="key">要删除的节点key值</param>
        /// <returns>0:删除失败,1:删除成功,-1:配置文件异常,-2系统异常,</returns>
        public static string DeleteIndexConfigValue(string path, string key)
        {
            string flag = "0";
            string indexConfigPath = path;
            if (string.IsNullOrEmpty(indexConfigPath))
                return flag = "-1";//配置文件为空
            if (!File.Exists(indexConfigPath))
                return flag = "-1";//配置文件不存在

            ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
            ecf.ExeConfigFilename = indexConfigPath;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
            try
            {
                config.AppSettings.Settings.Remove(key);
                config.Save(ConfigurationSaveMode.Modified);
                flag = "1";
            }
            catch (Exception)
            {
                flag = "-2";//系统异常
            }
            return flag;
        }
    }
}

 

 

调用方式:

    string ss = Chain.Common.DIYConfigHelper.GetIndexConfigValue(HttpRuntime.AppDomainAppPath.ToString() + "DIY.config", "14");//获取节点值
    bool tt = Chain.Common.DIYConfigHelper.SetIndexConfigValue(HttpRuntime.AppDomainAppPath.ToString() + "DIY.config", "14", "5");//修改节点值
    Chain.Common.DIYConfigHelper.AddIndexConfigValue(HttpRuntime.AppDomainAppPath.ToString() + "DIY.config", "14", "123123123123");//添加节点和值

string mm=Chain.Common.DIYConfigHelper.DeleteIndexConfigValue(HttpRuntime.AppDomainAppPath.ToString() + "DIY.config", "14");//删除指定值的节点
 

 

DIY.config文件的内容

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
     <add key="15" value="663CFB4AF7AE2A91B14587C31B3DE60AF38AED2E63F5040C5D453CBC704162B8ACDD7A7D67A95FA0" /> 
    <add key="14" value="156D7DB054ABBF9B321B1E8982130FDA3420475BC524C4259C55A8CEA4F884DE649FD16284A1053F" />
  </appSettings>
  <connectionStrings />
</configuration>

 

posted @ 2018-08-25 16:48  风琴~云淡  阅读(2831)  评论(0编辑  收藏  举报