在运行时更改默认的app.config

在运行时更改默认的app.config,第1张

在运行时更改默认的app.config

如果在首次使用配置系统之前就使用了链接问题中的技巧,则该技巧是可行的。在那之后,它不再起作用了。
原因:
存在一个

ClientConfigPaths
缓存路径的类。因此,即使使用更改了路径
SetData
,也不会重新读取它,因为已经存在缓存的值。解决方案是也删除这些:

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);        }    }}

用法是这样的:

// the default app.config is used.using(AppConfig.Change(tempFileName)){    // the app.config in tempFileName is used}// the default app.config is used.

如果要在整个应用程序运行时更改使用的app.config,只需

AppConfig.Change(tempFileName)
在应用程序开始处放置而不使用的位置即可。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5441145.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存