-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigLib.cs
94 lines (72 loc) · 2.47 KB
/
ConfigLib.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.IO;
using System.Xml;
using Newtonsoft.Json;
using Formatting = Newtonsoft.Json.Formatting;
namespace Kanna
{
public class ConfigLib<T> where T : class
{
private string ConfigCache;
public ConfigLib(string configPath, int RefreshInterval = 1000)
{
ConfigPath = configPath;
var PathToWatch = Path.GetDirectoryName(ConfigPath);
if (PathToWatch != null)
{
var watcher = new FileSystemWatcher(PathToWatch, Path.GetFileName(ConfigPath))
{
NotifyFilter = NotifyFilters.LastWrite,
EnableRaisingEvents = true
};
watcher.Changed += UpdateConfig;
}
if (!File.Exists(ConfigPath))
{
File.WriteAllText(ConfigPath, JsonConvert.SerializeObject(Activator.CreateInstance(typeof(T)), Formatting.Indented));
}
InternalConfig = JsonConvert.DeserializeObject<T>(File.ReadAllText(ConfigPath));
var timer = new System.Timers.Timer(RefreshInterval);
ConfigCache = JsonConvert.SerializeObject(InternalConfig, Formatting.Indented);
timer.Elapsed += (sender, e) =>
{
if (JsonConvert.SerializeObject(InternalConfig, Formatting.Indented) != ConfigCache)
{
ConfigCache = JsonConvert.SerializeObject(InternalConfig, Formatting.Indented);
SaveConfig();
//MessageBox.Show("Saved!");
}
};
timer.Enabled = true;
timer.Start();
}
private string ConfigPath
{
get;
}
public T InternalConfig
{
get; private set;
}
public event Action OnConfigUpdated;
private void UpdateConfig(object obj, FileSystemEventArgs args)
{
try
{
var ConfigData = File.ReadAllText(ConfigPath);
if (ConfigCache != ConfigData)
{
InternalConfig = JsonConvert.DeserializeObject<T>(ConfigData);
OnConfigUpdated?.Invoke();
}
}
catch
{
}
}
public void SaveConfig()
{
File.WriteAllText(ConfigPath, JsonConvert.SerializeObject(InternalConfig, Formatting.Indented));
}
}
}