现定义一个方法 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>
来源: http://www.bubuko.com/infodetail-2741975.html