windows service - config file

前提是你 提交于 2019-12-29 06:20:28

问题


I know this has probably been asked before but I can't seem to find the right answer for me.

I have a windows service named foobar.exe. I have an application configuration file named foobar.exe.config in the same folder.

Is the config file only read at startup?

I would like to make changes to the config file without having to restart the service but that is the only way I can get the new settings read.

What am I doing wrong?

Can a windows service have a dynamic config file?


回答1:


.NET applications will read their config files at startup and cache them for performance reasons.

I see two basic ways around this:

  • in your service, keep track of the last update date/time for the config file. Check this last update date regularly and if you detect a change, re-load the config file

  • a Windows NT service can respond to a special OnCustomCommand event. You could implement such an event handler to reload the config, and when you do change the config, you could have a small utility to signal to your service that the config has changed and send that "custom command" to your service




回答2:


Assuming your windows service was written with .NET:

Configuration files are only read at startup. If you change values in the configuration, you will need to restart the service in order for them to be picked up.

If you want to have dynamic configuration, you will need to implement this yourself - polling the filesystem to see if the configuration file changed and apply the changes.




回答3:


You may need to look at using FileSystemWatcher. See pseudo-c#-code example below.

private FileSystemWatcher _myWatcher;

protected override void OnStart(string[] args)
{
_myWatcher = new FileSystemWatcher();
_myWatcher.Path = path to config file;
_myWatcher.Changed += new FileSystemEventHandler(myWatcherFileChanged);
_myWatcher.NotifyFilter = NotifyFilters.LastWrite;
_myWatcher.EnableRaisingEvents = true;

}

protected override void OnStop()
{
    _myWatcher.EnableRaisingEvents = false;
}

private void myWatcherFileChanged(object sender, FileSystemEventArgs e)
{
...
}


来源:https://stackoverflow.com/questions/5104992/windows-service-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!