获取或设置config节点值

ExeConfigurationFileMap 这个类提供了修改、获取指定 config 的功能;
新建一个 ExeConfigurationFileMap 的实例 ecf ;
并设置 ExeConfigFilename 属性为要操作的 config 文件路径;
使用 ConfigurationManager.OpenMappedExeConfiguration 方法得到操对象 Configuration config
调用 Configuration 对象实例提供的 config.AppSettings.Settings[key].Value 可以修改或者获取 appsetting 的值了;
如果修改需要调用一下保存方法,config.Save();

/// <summary>
/// 获取自定义 index.config 文件中的 appsetting 节点值
/// </summary>
/// <param name="key">节点名称</param>
/// <returns></returns>
public static string GetIndexConfigValue(string key)
{
 string indexConfigPath = @"D:\indexConfig";
 if (indexConfigPath.IsNullOrEmpty())
  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="key">节点名称</param>
/// <returns></returns>
public static bool SetIndexConfigValue(string key,string value)
{
 string indexConfigPath = @"D:\indexConfig";
 if (indexConfigPath.IsNullOrEmpty())
  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;
}

转载请保留:http://blog.csdn.NET/xxj_jing/article/details/7682565

posted @ 2016-12-21 11:14  wangqiquan  阅读(659)  评论(0编辑  收藏  举报