forked from jeremybytes/SlideShow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SettingsManager.cs
45 lines (38 loc) · 1.39 KB
/
SettingsManager.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
using System.IO;
using System.Reflection;
using System.Text.Json;
namespace SlideShow;
public abstract class SettingsManager<T> where T : SettingsManager<T>, new()
{
public static T Instance { get; private set; } = new();
private static readonly JsonSerializerOptions serializerOptions = new() { WriteIndented = true };
private static readonly string filePath = GetLocalFilePath();
private static string GetLocalFilePath()
{
string appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string appName = Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty;
string fileName = $"{typeof(T).Name}.json";
return Path.Combine(appData, appName, fileName);
}
public static void Load()
{
if (File.Exists(filePath))
{
var data = JsonSerializer.Deserialize<T>(File.ReadAllText(filePath));
if (data != null)
{
Instance = data;
}
}
}
public static void Save()
{
var directory = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string json = JsonSerializer.Serialize(SettingsManager<T>.Instance, serializerOptions);
File.WriteAllText(filePath, json);
}
}