-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigManager.cs
More file actions
55 lines (49 loc) · 1.48 KB
/
ConfigManager.cs
File metadata and controls
55 lines (49 loc) · 1.48 KB
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
using System.IO;
using System;
using System.Text.Json;
using System.Windows.Forms;
using System.Diagnostics;
public static class ConfigManager
{
private static readonly string ConfigFilePath = Path.Combine( // set the expected config filepath
AppDomain.CurrentDomain.BaseDirectory, "config.json");
private static AppConfig? _config;
// Lazily loads config on first access
public static AppConfig Config => _config ??= Load();
public static AppConfig Load() // load and deserialise config file
{
if (File.Exists(ConfigFilePath))
{
try
{
string json = File.ReadAllText(ConfigFilePath);
return JsonSerializer.Deserialize<AppConfig>(json) ?? new AppConfig();
}
catch
{
return new AppConfig();
}
}
return new AppConfig();
}
public static void Save() // serialise and write config to file
{
try
{
string json = JsonSerializer.Serialize(Config, new JsonSerializerOptions
{
WriteIndented = true
});
File.WriteAllText(ConfigFilePath, json);
}
catch (Exception ex)
{
MessageBox.Show($"Failed to save settings: {ex.Message}");
}
}
public static void Reload()
{
_config = Load(); // Reload config from disk
// Debug.WriteLine(JsonSerializer.Serialize(Config));
}
}