• 获取或设置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

  • 相关阅读:
    实用小软件
    没有找到MSVCP71.dll,迅雷5无法进行离线下载,P2P Seacher无法连入emule网络
    PSP2000V3版5.03系统误删PSP文件夹的拯救方案
    图书馆图书检索的小技巧
    thinkpad指点杆(trackpoint)在WPS的word文档中失效的解决办法
    笔记本电池死而复生
    调试Page.IsPostBack,感觉好奇怪
    OleDbSchemaGuid.Columns返回DataTable介绍
    静态类生命周期的问题
    IE中居中,FF中出问题
  • 原文地址:https://www.cnblogs.com/makqiq/p/6206968.html
Copyright © 2020-2023  润新知