FlexitimeTracker/DataCenter_Windows/WindowsDataCenter/ConfigMonitor/ConfigMonitor.cs

89 lines
2.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
namespace ConfigMonitor
{
public class ConfigMonitor
{
private readonly FileSystemWatcher _watcher;
private DateTime _lastChange;
public ConfigMonitor(string configFilePath)
{
if (configFilePath == null)
{
throw new ArgumentNullException(nameof(configFilePath));
}
_lastChange = DateTime.MinValue;
//var configFile = string.Concat(System.Reflection.Assembly.GetEntryAssembly().Location, ".config");
if (File.Exists(configFilePath))
{
_watcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath))
{
EnableRaisingEvents = true
};
_watcher.Changed += Watcher_Changed;
}
}
~ConfigMonitor()
{
_watcher.EnableRaisingEvents = false;
_watcher.Changed -= Watcher_Changed;
_watcher.Dispose();
}
public void Stop()
{
_watcher.EnableRaisingEvents = false;
_watcher.Changed -= Watcher_Changed;
_watcher.Dispose();
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
if ((DateTime.Now - _lastChange).Seconds <= 5 || IsFileLocked(e.FullPath)) return;
var monitoredSections = ConfigurationManager.AppSettings["monitoredSections"];
if (monitoredSections!= null)
{
IEnumerable<string> sections = monitoredSections.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (sections.Any())
{
foreach (var section in sections)
{
ConfigurationManager.RefreshSection(section);
}
}
}
else
{
ConfigurationManager.RefreshSection("appSettings");
}
_lastChange = DateTime.Now;
}
private bool IsFileLocked(string filePath)
{
FileStream stream = null;
try
{
stream = File.OpenRead(filePath);
}
catch (IOException)
{
return true;
}
finally
{
stream?.Close();
}
return false;
}
}
}