-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppConfig.cs
More file actions
66 lines (52 loc) · 2.01 KB
/
Copy pathAppConfig.cs
File metadata and controls
66 lines (52 loc) · 2.01 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
56
57
58
59
60
61
62
63
64
65
66
using System.Text.Json;
namespace BatteryDown;
internal sealed class AppConfig
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
};
public int DelaySeconds { get; set; }
public int ShutdownDelaySeconds { get; set; } = 60;
public bool ShutdownImmediatelyWhenLocked { get; set; }
public static string DirectoryPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "BatteryDown");
public static string FilePath => Path.Combine(DirectoryPath, "config.json");
public static AppConfig Load() => LoadFrom(FilePath);
public static AppConfig LoadFrom(string filePath)
{
try
{
if (File.Exists(filePath))
{
var json = File.ReadAllText(filePath);
var config = JsonSerializer.Deserialize<AppConfig>(json) ?? new AppConfig();
using var document = JsonDocument.Parse(json);
if (!document.RootElement.TryGetProperty(nameof(DelaySeconds), out _) &&
document.RootElement.TryGetProperty("DelayMinutes", out var oldDelay) &&
oldDelay.TryGetInt32(out var oldDelayMinutes))
{
config.DelaySeconds = checked(oldDelayMinutes * 60);
}
return Normalize(config);
}
}
catch (JsonException)
{
// A damaged config should not prevent the user from opening the settings window.
}
return new AppConfig();
}
public void Save()
{
Normalize(this);
Directory.CreateDirectory(DirectoryPath);
File.WriteAllText(FilePath, JsonSerializer.Serialize(this, JsonOptions));
}
private static AppConfig Normalize(AppConfig config)
{
config.DelaySeconds = Math.Clamp(config.DelaySeconds, 0, 3600);
config.ShutdownDelaySeconds = Math.Clamp(config.ShutdownDelaySeconds, 10, 3600);
return config;
}
}