重新加载 .NET 配置文件
修改配置文件后需要重新加载。如何使用应用程序域来完成此操作?代码示例会很有用。
I need to reload the configuration file after modifying it. How this can be done using appdomains? A code sample would be useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您有以下配置文件:
让我们首先尝试简单的方法。以下应用程序将尝试每秒获取一次名为
test
的appSetting
的值,并打印其值:但是唉!当它运行时,您会注意到它不断打印
1
,并且没有获取任何更改。如果您将代码更新为以下内容,它将解决此问题,并且每当您更改它时它都会拾取更改:
Let's say you have the following config file:
Let's try the naive approach first. The following application will try to grab the value of the
appSetting
namedtest
once per second, and print its value:But alas! While this is running, you'll notice it keeps printing
1
, and doesn't pick up any changes.If you update your code to the following, it will fix this issue, and it will pick up changes whenever you change it:
ConfigurationManager.RefreshSection
可能适合你。ConfigurationManager.RefreshSection
might work for you.是的,有可能...取决于您访问配置文件的方式。
如果您依赖默认行为,那么答案是否。
但是,如果您通过项目通用方法的
static
属性访问配置,则可以重新加载它。我现在没有代码片段,但即使使用
FileSystemWatcher
检测config
文件中的更改。有一个警告,它仅适用于您直接通过代码访问的属性,当您执行此类操作时,自动配置不会重新加载。
Yes, it's possible... depending on HOW you access your configuration file.
If you rely on the default behavior, then the answer is NO.
However, if you access the configuration through a
static
property of method common to your project, then it's possible to reload it.I don't have the code snippet with me now, but I did something similar even using a
FileSystemWatcher
to detect changes in theconfig
file.There's one caveat, it works only with properties that you access directly through your code, automatic configuration will not be reloaded when you do such thing.
我实际上已经找到了给定问题的解决方案。下面是如何完成此操作的几行代码:
这里的关键点是 AppDomainSetup 类,它允许在要创建的程序集上设置配置文件属性。现在,我们可以监视配置文件“Target_Config.exe.config”的更改。当它改变时,上面创建的appdomain应该被卸载然后重新创建。
I have actually found the solution to the given problem. Below are fiew lines of code of how this can be done:
The key point here is the AppDomainSetup class, which allows to set the configurationfile property on the assembly to be created. Now, we can monitor the configuration file "Target_Config.exe.config" for changes. When it is changed, the above created appdomain should be unloaded and then recreated.