gpt4 book ai didi

c# - ConfigurationManager.RefreshSection ("appSettings") 无效

转载 作者:行者123 更新时间:2023-11-30 14:08:38 25 4
gpt4 key购买 nike

背景:我正在使用 Timer 在 Windows 服务中定期做一些工作。我希望定时器在运行时是可配置的。我唯一能做的就是在启动时配置它。

我的解决方案:我正在使用 app.config 来配置计时器的开始时间和周期:

  <appSettings>
<add key="StartTime" value="14:40:00"/>
<add key="Period" value="24:00:00"/>
</appSettings>

我正在使用 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
{
_fileSystemWatcher.EnableRaisingEvents = false;
ConfigurationManager.RefreshSection("appSettings");
foreach (var listener in configurationChangedListeners)
{
listener.NotifyConfigurationChanged();
}
}
finally
{
_fileSystemWatcher.EnableRaisingEvents = true;
}
}

最后,每个监听器都像这样获取其配置:

public void NotifyConfigurationChanged()
{
string strKeyName = "StartTime";
string startTime = ConfigurationManager.AppSettings[strKeyName];
// ...
}

还有问题:- 当我编辑文件时,文件观察器会触发事件,但是当我尝试获取新的 AppSettings 时,我正在读取旧值(从服务启动时开始)

奇怪的是,这个设置在某些时候起作用,然后却不起作用(据我所知没有更改代码)。

非常感谢任何帮助/建议。

最佳答案

问题的答案(经过大量搜索 :D)是使用 OpenExeConfiguration 而不是直接访问 AppSettings。据我了解,刷新后需要再次打开配置:

var appSettings = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings;
string setting = appSettings.Settings[strKeyName].Value;

虽然我第一次尝试时第一个变体在特定情况下工作,但我很肯定......

关于c# - ConfigurationManager.RefreshSection ("appSettings") 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34439625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com