如何在.net Windows应用程序中动态重新加载app.config?我需要动态地打开和关闭日志记录,而不仅仅是基于应用程序启动时的值.
ConfigurationManager.RefreshSection("appSettings")不起作用,我也尝试使用OpenExeConfiguration显式打开配置文件,但我总是在应用程序启动时获取缓存值,而不是当前值.
我接受了创建自定义配置部分的答案.作为旁注和愚蠢的错误 - 如果您从IDE运行,则更新app.config文件并期待更改是没有意义的.Yuo必须修改bin\debug文件夹中的.exe.config文件.卫生署!
背景:我使用计时器在 Windows 服务中定期执行一些工作。我希望计时器可以在运行时进行配置。我唯一能做的就是在启动时配置它。
我的解决方案:我使用 app.config 来配置计时器的开始时间和周期:
<appSettings>
<add key="StartTime" value="14:40:00"/>
<add key="Period" value="24:00:00"/>
</appSettings>
Run Code Online (Sandbox Code Playgroud)
我正在使用 FileSystemWatcher 来通知配置文件上的文件写入(将是 AppName.exe.config)
public ConfigWatcher(params object[] args)
{
configurationChangedListeners = new List<INotifyConfigurationChanged>();
string assemblyDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
NotifyFilters notifyFilters = NotifyFilters.LastWrite;
_fileSystemWatcher = new FileSystemWatcher()
{
Path = assemblyDirectory,
NotifyFilter = notifyFilters,
Filter = "*.config"
};
_fileSystemWatcher.Changed += OnChanged;
_fileSystemWatcher.EnableRaisingEvents = true;
if (args != null)
{
foreach (var arg in args)
{
AddListener(arg);
}
}
}
private void OnChanged(object source, System.IO.FileSystemEventArgs e)
{
try
{ …Run Code Online (Sandbox Code Playgroud)