-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathAbstractSettingsJson.cs
110 lines (90 loc) · 2.33 KB
/
AbstractSettingsJson.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
namespace RaceElement.Util;
public interface IGenericSettingsJson
{
}
public abstract class AbstractSettingsJson<T>
where T : IGenericSettingsJson
{
public abstract T Default();
public abstract string Path { get; }
public abstract string FileName { get; }
private readonly FileInfo _settingsFile;
public static T Cached { get; private set; }
protected AbstractSettingsJson()
{
_settingsFile = new(Path + FileName);
Cached = Get(false);
}
public T Get(bool cached = true)
{
if (cached && Cached != null)
return Cached;
if (!_settingsFile.Exists)
return Default();
try
{
using FileStream fileStream = _settingsFile.OpenRead();
Cached = ReadJson(fileStream);
return Cached;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return Default();
}
public void Save(T genericJson)
{
try
{
string jsonString = JsonConvert.SerializeObject(genericJson, Formatting.Indented);
if (!_settingsFile.Exists && !Directory.Exists(Path))
Directory.CreateDirectory(Path);
File.WriteAllText(Path + "\\" + FileName, jsonString);
Cached = genericJson;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
private T ReadJson(FileStream stream)
{
string jsonString = string.Empty;
try
{
using (StreamReader reader = new(stream))
{
jsonString = reader.ReadToEnd();
jsonString = jsonString.Replace("\0", "");
reader.Close();
stream.Close();
}
T t = JsonConvert.DeserializeObject<T>(jsonString);
if (t == null)
return Default();
return t;
}
catch (Exception e)
{
Debug.WriteLine(e);
}
return Default();
}
public void Delete()
{
try
{
if (_settingsFile.Exists)
_settingsFile.Delete();
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
}