栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在运行时更改默认的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)
在应用程序开始处放置而不使用的位置即可。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465650.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号