『随笔』C# 程序 修改 ConfigurationManager 后,不重启 刷新配置
基本共识:
ConfigurationManager 自带缓存,且不支持 写入。
如果 通过 文本写入方式 修改 配置文件,程序 无法刷新加载 最新配置。
PS. Web.config 除外:Web.config 修改后,网站会重启 (即 Web 程序 也无法在 运行时 刷新配置)。
为什么要在程序运行时,修改配置(刷新配置):
> 以前C++,VB 时代,用户在程序界面 勾选的配置,会写到 ini 文件。
> C# 自带 .exe.config 配置文件 —— 但是,C# 自带的 ConfigurationManager 不支持 运行时 修改,运行时刷新配置。
> 本文 提供工具类,彻底 解决 这个问题 —— 从此,用户手动勾选的配置 再也不用写入 ini,而是直接修改 .exe.config 文件,且立即刷新。
刷新 ConfigurationManager 配置 的 代码 有两种:
> 第一种:
ConfigurationManager.RefreshSection("appSettings"); //刷新 appSettings 节点 (立即生效)
ConfigurationManager.RefreshSection("connectionString"); //刷新 connectionString 节点 (无法生效 —— 可能是 微软处理时,因为 LocalSqlServer 这个默认配置 而导致的疏忽)
> 第二种:
FieldInfo fieldInfo = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
if (fieldInfo != null) fieldInfo.SetValue(null, ); //将配置文件 设置为: 未分析 状态, 配置文件 将会在下次读取 时 重新分析.
//立即生效,而且效果 明显 —— 就喜欢这种 暴力做法。
一起反编译 ConfigurationManager 代码:
> 首先 下载 ILSpy 或 Reflector (本文使用的是 ILSpy.)
> 打开 ILSpy 搜索 ConfigurationManager,执行如下操作:





> 编写 反射代码,刷新 配置文件数据。(具体代码 在 文章最开始。)
额外提供 配置文件 修改的 工具类代码:
以下代码 实现如下功能:
> 执行 配置写入操作时,自动创建 .exe.config 文件,自动创建 appSettings connectionString 节点。
> .exe.config 写入配置时,如果 相同的 key name 存在,则修改,不存在 则创建。
> 额外的 审美操作:
> 很多人习惯 appSettings 显示在 connectionString 前面。
> 很多人习惯 appSettings 在 最前面。
> appSettings 必须在 configSections 后面。(configSections 配置文件 扩展配置节点,只能写在第一个,否则 程序报错。)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Xml; namespace InkFx.Utils
{
public partial class Tools
{ private static ConfigAppSetting m_AppSettings;
private static ConfigConnectionStrings m_ConnectionStrings; public static ConfigAppSetting AppSettings
{
get
{
if (m_AppSettings == null)
{
m_AppSettings = new ConfigAppSetting();
m_AppSettings.AppSettingChanged += OnAppSettingChanged;
}
return m_AppSettings;
}
}
public static ConfigConnectionStrings ConnectionStrings
{
get
{
if (m_ConnectionStrings == null)
{
m_ConnectionStrings = new ConfigConnectionStrings();
m_ConnectionStrings.ConnectionStringsChanged += OnConnectionStringsChanged;
}
return m_ConnectionStrings;
}
} private static void OnAppSettingChanged(string name, string value)
{
string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
if (!File.Exists(configPath))
{
const string content = @"<?xml version=""1.0""?><configuration></configuration>";
File.WriteAllText(configPath, content, Encoding.UTF8);
} XmlDocument doc = new XmlDocument();
doc.Load(configPath); XmlNode nodeConfiguration = doc.SelectSingleNode(@"configuration");
if (nodeConfiguration == null)
{
nodeConfiguration = doc.CreateNode(XmlNodeType.Element, "configuration", string.Empty);
doc.AppendChild(nodeConfiguration);
} XmlNode nodeAppSettings = nodeConfiguration.SelectSingleNode(@"appSettings");
if (nodeAppSettings == null)
{
nodeAppSettings = doc.CreateNode(XmlNodeType.Element, "appSettings", string.Empty);
if (!nodeConfiguration.HasChildNodes)
nodeConfiguration.AppendChild(nodeAppSettings);
else
{
//configSections 必须放在 第一个, 所以得 避开 configSections
XmlNode firstNode = nodeConfiguration.ChildNodes[];
bool firstNodeIsSections = string.Equals(firstNode.Name, "configSections", StringComparison.CurrentCultureIgnoreCase); if (firstNodeIsSections)
nodeConfiguration.InsertAfter(nodeAppSettings, firstNode);
else
nodeConfiguration.InsertBefore(nodeAppSettings, firstNode);
}
} string xmlName = FormatXmlStr(name);
XmlNode nodeAdd = nodeAppSettings.SelectSingleNode(@"add[@key='" + xmlName + "']");
if (nodeAdd == null)
{
nodeAdd = doc.CreateNode(XmlNodeType.Element, "add", string.Empty);
nodeAppSettings.AppendChild(nodeAdd);
} XmlElement nodeElem = (XmlElement)nodeAdd;
nodeElem.SetAttribute("key", name);
nodeElem.SetAttribute("value", value);
doc.Save(configPath); try { ConfigurationManager.RefreshSection("appSettings"); } catch (Exception) { }
}
private static void OnConnectionStringsChanged(string name, string value)
{
string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
if (!File.Exists(configPath))
{
const string content = @"<?xml version=""1.0""?><configuration></configuration>";
File.WriteAllText(configPath, content, Encoding.UTF8);
} XmlDocument doc = new XmlDocument();
doc.Load(configPath); XmlNode nodeConfiguration = doc.SelectSingleNode(@"configuration");
if (nodeConfiguration == null)
{
nodeConfiguration = doc.CreateNode(XmlNodeType.Element, "configuration", string.Empty);
doc.AppendChild(nodeConfiguration);
} XmlNode nodeAppSettings = nodeConfiguration.SelectSingleNode(@"appSettings");
XmlNode nodeConnectionStrings = nodeConfiguration.SelectSingleNode(@"connectionStrings");
if (nodeConnectionStrings == null)
{
nodeConnectionStrings = doc.CreateNode(XmlNodeType.Element, "connectionStrings", string.Empty);
if (!nodeConfiguration.HasChildNodes)
nodeConfiguration.AppendChild(nodeConnectionStrings);
else
{
//优先将 connectionStrings 放在 appSettings 后面
if (nodeAppSettings != null)
nodeConfiguration.InsertAfter(nodeConnectionStrings, nodeAppSettings);
else
{
//如果 没有 appSettings 节点, 则 configSections 必须放在 第一个, 所以得 避开 configSections
XmlNode firstNode = nodeConfiguration.ChildNodes[];
bool firstNodeIsSections = string.Equals(firstNode.Name, "configSections", StringComparison.CurrentCultureIgnoreCase); if (firstNodeIsSections)
nodeConfiguration.InsertAfter(nodeConnectionStrings, firstNode);
else
nodeConfiguration.InsertBefore(nodeConnectionStrings, firstNode);
}
}
} string xmlName = FormatXmlStr(name);
XmlNode nodeAdd = nodeConnectionStrings.SelectSingleNode(@"add[@name='" + xmlName + "']");
if (nodeAdd == null)
{
nodeAdd = doc.CreateNode(XmlNodeType.Element, "add", string.Empty);
nodeConnectionStrings.AppendChild(nodeAdd);
} XmlElement nodeElem = (XmlElement)nodeAdd;
nodeElem.SetAttribute("name", name);
nodeElem.SetAttribute("connectionString", value);
doc.Save(configPath); try
{
ConfigurationManager.RefreshSection("connectionString"); //RefreshSection 无法刷新 connectionString 节点
FieldInfo fieldInfo = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
if (fieldInfo != null) fieldInfo.SetValue(null, ); //将配置文件 设置为: 未分析 状态, 配置文件 将会在下次读取 时 重新分析.
}
catch (Exception) { }
} private static string FormatXmlStr(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty; string result = value
.Replace("<", "<")
.Replace(">", ">")
.Replace("&", "&")
.Replace("'", "'")
.Replace("\"", """);
return result;
//< < 小于号
//> > 大于号
//& & 和
//' ' 单引号
//" " 双引号
} public class ConfigAppSetting
{
private readonly InnerIgnoreDict<string> m_Hash = new InnerIgnoreDict<string>(); public string this[string name]
{
get
{
string value = m_Hash[name];
if (string.IsNullOrWhiteSpace(value))
{
try { value = ConfigurationManager.AppSettings[name]; } catch(Exception) { }
m_Hash[name] = value;
return value;
}
return value;
}
set
{
m_Hash[name] = value;
try{ ConfigurationManager.AppSettings[name] = value; } catch(Exception) { }
if (AppSettingChanged != null) AppSettingChanged(name, value);
}
}
public AppSettingValueChanged AppSettingChanged; public delegate void AppSettingValueChanged(string name, string value);
}
public class ConfigConnectionStrings
{
private readonly InnerIgnoreDict<ConnectionStringSettings> m_Hash = new InnerIgnoreDict<ConnectionStringSettings>(); public string this[string name]
{
get
{
ConnectionStringSettings value = m_Hash[name];
if (value == null || string.IsNullOrWhiteSpace(value.ConnectionString))
{
try { value = ConfigurationManager.ConnectionStrings[name]; } catch (Exception) { }
m_Hash[name] = value;
return value == null ? string.Empty : value.ConnectionString;
}
return value.ConnectionString;
}
set
{ ConnectionStringSettings setting = new ConnectionStringSettings();
setting.Name = name;
setting.ConnectionString = value;
m_Hash[name] = setting;
//try { ConfigurationManager.ConnectionStrings[name] = setting; } catch (Exception) { }
if (ConnectionStringsChanged != null) ConnectionStringsChanged(name, value);
}
}
public ConnectionStringsValueChanged ConnectionStringsChanged; public delegate void ConnectionStringsValueChanged(string name, string value);
} private class InnerIgnoreDict<T> : Dictionary<string, T>
{
public InnerIgnoreDict(): base(StringComparer.CurrentCultureIgnoreCase)
{
} #if (!WindowsCE && !PocketPC)
public InnerIgnoreDict(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif private readonly object getSetLocker = new object();
private static readonly T defaultValue = default(T); public new T this[string key]
{
get
{
if (key == null) return defaultValue;
lock (getSetLocker) //为了 多线程的 高并发, 取值也 加上 线程锁
{
T record;
if (TryGetValue(key, out record)) return record;
else return defaultValue;
}
}
set
{
try
{
if (key != null)
{
lock (getSetLocker)
{
//if (!value.Equals(default(T)))
//{
if (base.ContainsKey(key)) base[key] = value;
else base.Add(key, value);
//}
//else
//{
// base.Remove(key);
//}
}
}
}
catch (Exception) { }
}
}
} }
}
工具类使用代码:
static void Main(string[] args)
{
Tools.AppSettings["Test"] = "Love"; //修改配置文件
Console.WriteLine(ConfigurationManager.AppSettings["Test"]); //传统方式 读取配置文件
Console.WriteLine(Tools.AppSettings["Test"]); //工具类 读取配置文件 Tools.ConnectionStrings["ConnString"] = "Data Source=127.0.0.1;Initial Catalog=master;User=sa;password=123.com;";
Console.WriteLine(ConfigurationManager.ConnectionStrings["ConnString"]);
Console.WriteLine(Tools.ConnectionStrings["ConnString"]); Tools.AppSettings["Test"] = "<Love>";
Console.WriteLine(ConfigurationManager.AppSettings["Test"]);
Console.WriteLine(Tools.AppSettings["Test"]); Console.ReadKey();
}
执行结果:

配置文件变化:
> 程序执行前,删除配置文件。
> 程序执行后,自动生成配置文件。

『随笔』C# 程序 修改 ConfigurationManager 后,不重启 刷新配置的更多相关文章
- 解决Windows服务修改配置文件后必须重启的问题
原文地址:http://www.cnblogs.com/jeffwongishandsome/archive/2011/04/24/2026381.html 解决方法:读取配置文件前先刷新文件 ...
- Node.js热部署代码,实现修改代码后自动重启服务方便实时调试
写PHP等脚本语言的时候,已经习惯了修改完代码直接打开浏览器去查看最新的效果.而Node.js 只有在第一次引用时才会去解析脚本文件,以后都会直接访问内存,避免重复载入,这种设计虽然有利于提高性能,却 ...
- spring boot修改代码后无需重启设置,在开发时实现热部署
Spring Boot在开发时实现热部署(开发时修改文件保存后自动重启应用)(spring-boot-devtools) 热部署是什么 大家都知道在项目开发过程中,常常会改动页面数据或者修改数据结构, ...
- The Data Way Vol.2 | 做个『单纯』的程序员还真不简单
关于「The Data Way」 「The Data Way」是由 SphereEx 公司出品的一档播客节目.这里有开源.数据.技术的故事,同时我们关注开发者的工作日常,也讨论开发者的生活日常:我们聚 ...
- 『随笔』Socket 链接 必须 上下行 同时使用
结论: > Socket 理论上 支持 只上行,或者 只下行. > 心跳包 必须是 上下行的 —— 心跳包请求(上行) - 心跳包响应(下行). > 如果 长时间 只有单向链接(只发 ...
- 『随笔』WCF开发那些需要注意的坑
执行如下 批处理:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\svcutil.exe" http://127.0.0.1: ...
- 『随笔』.Net 底层 数组[] 的 基本设计探秘 512 子数组
static void Main(string[] args) { Console.ReadKey(); //初始化数组 不会立即开辟内存字节, 只有实际给数组赋值时 才会开辟内存 // //猜测数组 ...
- Android程序意外Crash后自动重启
1.自定义UncaughtExceptionHandler public class UnCeHandler implements UncaughtExceptionHandler { private ...
- Maven项目热部署,修改代码后不用重启tomcat服务器
只需要在pom.xml文件中添加 <build> <finalName>MySSM</finalName> <!-- 指定部署的服务器类型 --> &l ...
随机推荐
- 命令行方式使用abator.jar生成ibatis相关代码和sql语句xml文件
最近接手一个老项目,使用的是数据库是sql server 2008,框架是springmvc + spring + ibatis,老项目是使用abator插件生成的相关代码,现在需要增加新功能,要添加 ...
- 一个SharePoint定时器 (SPJobDefinition)
需要写一个自定义的sharepoint timer job, 目的是要定时到Site Collection Images这个List里检查图片的过期日期,如果即将过期的话,需要发送email到相关的人 ...
- C#拖放实现餐饮系统转台操作
转台是餐饮系统中常用的操作,一般系统都是右键选择弹出目标台界面,然后选择目标台确定,现在我们把需要转的台通过拖动到目标台图标上面就可以实现前面的操作,简单快捷. 转台操作时: 转台成功后: /// & ...
- 2012年 蓝桥杯预赛 java 本科 题目
2012年 蓝桥杯预赛 java 本科 考生须知: l 考试时间为4小时. l 参赛选手切勿修改机器自动生成的[考生文件夹]的名称或删除任何自动生成的文件或目录,否则会干扰考试系统正确采集您的解答 ...
- linux搭建一个配置简单的nginx反向代理服务器 2个tomcat
1.我们只要实现访问nginx服务器能跳转到不同的服务器即可,我本地测试是这样的, 在nginx服务器里面搭建了2个tomcat,2个tomcat端口分别是8080和8081,当我输入我nginx服务 ...
- 原始的2文件的makefile错误
从来没系统的看过makefile文档,平时属于复制模板,用完即忘,下午尝试按自己的理解写一个最简单的makefile,含2个.c文件,1个.h文件,费了个把小时,参考别人的文章才弄出来,特记录. ma ...
- 使用Azure Automation(自动化)定时关闭和启动虚拟机
1. 概述 作为Windows Azure的用户,使用Azure的过程中,最担心的事情就是还没到月底,预设的费用就快消耗完了(下面两张账单图是我最讨厌看到的).但是仔细分析自己的费用列表,发现绝大部分 ...
- tarjan算法求割点cojs 8
tarjan求割点:cojs 8. 备用交换机 ★★ 输入文件:gd.in 输出文件:gd.out 简单对比时间限制:1 s 内存限制:128 MB [问题描述] n个城市之间有通讯网 ...
- NP完全问题 NP-Completeness
原创翻译加学习笔记,方便国人学习算法知识! 原文链接http://www.geeksforgeeks.org/np-completeness-set-1/ 我们已经找到很多很高效的算法来解决很难得问题 ...
- 2014 Super Training #9 F A Simple Tree Problem --DFS+线段树
原题: ZOJ 3686 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3686 这题本来是一个比较水的线段树,结果一个ma ...