运行时动态修改默认 app.config
问题描述:
开发一个解决方案,能够动态地将配置节从动态加载的应用程序模块加载到新的内存中 app.config,确保应用程序透明地使用修改后的配置,而不会覆盖默认的 app.config。
解决方案:
相关问题建议使用 SetData
方法更改配置系统路径,但这仅在配置系统首次使用之前执行时有效。为了完全解决这个问题,还需要清除缓存的配置值。
实现:
以下代码演示如何实现所需的行为:
<code class="language-csharp">using System; using System.Configuration; using System.Linq; using System.Reflection; public abstract class AppConfig : IDisposable { public static AppConfig Change(string path) { return new ChangeAppConfig(path); } public abstract void Dispose(); private class ChangeAppConfig : AppConfig { private readonly string oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString(); private bool disposedValue; public ChangeAppConfig(string path) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path); ResetConfigMechanism(); } public override void Dispose() { if (!disposedValue) { AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig); ResetConfigMechanism(); disposedValue = true; } GC.SuppressFinalize(this); } private static void ResetConfigMechanism() { typeof(ConfigurationManager) .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, 0); typeof(ConfigurationManager) .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); typeof(ConfigurationManager) .Assembly.GetTypes() .Where(x => x.FullName == "System.Configuration.ClientConfigPaths") .First() .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) .SetValue(null, null); } } }</code>
使用方法:
要临时修改特定范围的 app.config:
<code class="language-csharp">using (AppConfig.Change(tempFileName)) { // 应用程序使用修改后的 app.config }</code>
要永久更改整个运行时的 app.config:
<code class="language-csharp">// 应用程序使用修改后的 app.config AppConfig.Change(tempFileName);</code>
以上是如何在运行时动态修改默认的app.config?的详细内容。更多信息请关注PHP中文网其他相关文章!