What I'm wanting to do is create a file watcher that is monitoring for any changes in my services config file. When it detects any changes, the service should restart automatically so the changes can get picked up. However, I'm struggling to get the file watcher to notice that any changes have been made.
Here is my watcher code:
private void WatchConfigurationFile(string path)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "Project.MyService.exe.config"; // name of the file I'm wanting to watch
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
Then for the OnChanged method:
private void OnChanged(object source, FileSystemEventArgs e)
{
Log.Info("A change in the config has been found. Stopping Service");
ServiceController service = new ServiceController("MyService");
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(20);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch(Exception ex)
{
// ...
Log.Error("Error restarting service: " + ex.Message);
}
}
Finally I am calling all of the above with the following call:
public void Run()
{
WatchConfigurationFile("..\\InstallFolder\\MyService\\");
}
The Run
method is already used with in my service. I have the service running on a timer of which Run
gets called at the end of each count down. This method already has other method calls in there, so I know that the Run
method is working.
What is it I'm doing wrong with? I've got a funny feeling that my path may be incorrect as the config is in the same location as the service itself. But if someone else is able to shed light on this, it would be appreciated.