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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM