.net获取/修改配置文件/web.config

 配置实体类 (属性名称与配置项一致即可):

 public class WechatConfig
    {
   public string A{ get; set; }
  public string B{ get; set; }
  public string C{ get; set; }

}

获取配置信息

var configInfo = new WechatConfig();
            Configuration _Config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection _AppSettings = _Config.AppSettings;

            var props = configInfo.GetType().GetProperties();

            System.Reflection.PropertyInfo[] properties = configInfo.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                var config = _AppSettings.Settings[name];
                item.SetValue(configInfo, config.Value);
            }

设置配置信息

Configuration _Config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection _AppSettings = _Config.AppSettings;
            var props = param.GetType().GetProperties();
            foreach (var item in props)
            {
                var key = item.Name;
                var value = param.GetType().GetProperty(key).GetValue(param, null);
                if (_AppSettings.Settings[key] != null)
                    _AppSettings.Settings.Remove(key);
                _AppSettings.Settings.Add(key, value.ToString());
            }
            _Config.Save();

注意:

 如果有些配置项是在Application_Start加载使用的话,设置配置信息后需要重启服务才会生效,很明显十分不方便。

 所以最好封装需要使用配置数据的功能,在设置完配置项后调用一次即可

例如:使用盛派SDK需要在Application_Start全局注册一下微信信息,当我通过以上方法修改了微信配置时,再次调用一下我封装的盛派注册微信信息方法即可即时更新配置数据。

原文地址:https://www.cnblogs.com/ncellit/p/12689765.html