標籤:connect set ace help pdo dex using exe 不為
現定義一個方法 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 節點值 /// </summary> /// <param name="path">config檔案的路徑</param> /// <param name="key">節點名稱</param> /// <returns>節點名稱的值</returns> public static string GetIndexConfigValue(string path, string key) { 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); return config.AppSettings.Settings[key].Value; } /// <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; } }}
調用方式:
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");
DIY.config檔案的內容
<?xml version="1.0" encoding="utf-8"?><configuration> <appSettings> <add key="15" value="663CFB4AF7AE2A91B14587C31B3DE60AF38AED2E63F5040C5D453CBC704162B8ACDD7A7D67A95FA0" /> <add key="14" value="156D7DB054ABBF9B321B1E8982130FDA3420475BC524C4259C55A8CEA4F884DE649FD16284A1053F" /> </appSettings> <connectionStrings /></configuration>
C# 如何擷取自訂的config中節點的值,並修改節點的值