zoukankan      html  css  js  c++  java
  • 获取或设置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

  • 相关阅读:
    sgg_3_hibernate详解
    sgg_2_hibernate开发步骤
    sgg_1_hibernate概述
    cookie
    exchange 普通用户可以创建通讯组
    DC 维护常用工具命令DCdiag
    cp 复制不覆盖
    powershell 结果输出显示为……
    获得用户完整的autodiscover配置文件
    【转】outlook 2016 配置自动发现
  • 原文地址:https://www.cnblogs.com/makqiq/p/6206968.html
Copyright © 2011-2022 走看看