-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettingManager.cs
74 lines (67 loc) · 2.3 KB
/
SettingManager.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
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;
namespace MiLauncherFW
{
/// <summary>
/// Provides functionality to save(load) an object to to(from) specified file with <see cref="JsonSerializer"/>."
/// </summary>
// Used to save(load) both a set of searched files and Application Settings
internal class SettingManager
{
//
// Save
//
private static JsonSerializerOptions writeOptions = new JsonSerializerOptions() {
WriteIndented = true
};
public static void SaveSettings<T>(T settingsObject, string path, bool escaping = true)
{
// Fire and forget pattern
Task.Run(() =>
{
if (!escaping) writeOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
// To minimize risk of file corruption, create temp file and then rename it
var tempFileName = path + ".temp";
File.WriteAllText(tempFileName, JsonSerializer.Serialize(settingsObject, writeOptions));
try {
File.Delete(path);
}
catch (Exception e) {
Logger.LogError(e.Message);
}
try {
File.Move(tempFileName, path);
}
catch (Exception e) {
Logger.LogError(e.Message);
}
Logger.LogInfo($"SaveSettings finished: {path}");
});
}
public static void SaveSettingsNoEscape<T>(T settingsObject, string path)
{
SaveSettings(settingsObject, path, false);
}
//
// Load
//
private static JsonSerializerOptions readOptions = new JsonSerializerOptions() {
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
public static T LoadSettings<T>(string path)
{
try {
return JsonSerializer.Deserialize<T>(File.ReadAllText(path), readOptions);
}
catch (Exception e) {
Logger.LogError(e.Message);
return default;
}
}
}
}