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
|
namespace OnekoOnline;
class ConfigFile
{
public readonly string Path;
readonly Dictionary<string, string> ConfigOptions = [];
bool OptionChanged = false;
const string TopLine = "# OnekoOnline Config File";
public ConfigFile(string path)
{
Path = path;
if (!File.Exists(Path)) {
Console.WriteLine("Config file does not exist, creating one.");
File.WriteAllText(Path, TopLine);
OptionChanged = true;
return;
}
string[] fileContents = File.ReadAllLines(Path);
foreach (string line in fileContents) {
if (line[0] == '#' || !line.Contains('=') || line.Length < 3) continue;
string key = line[0..line.IndexOf('=')];
string value = line[(line.IndexOf('=')+1)..];
ConfigOptions.Add(key, value);
}
}
public void SaveFile()
{
if (!OptionChanged) return;
List<string> linesToWrite = [TopLine];
foreach (KeyValuePair<string, string> pair in ConfigOptions.OrderBy(k => k.Key)) linesToWrite.Add(pair.Key + "=" + pair.Value);
File.WriteAllLines(Path, linesToWrite);
OptionChanged = false;
}
public T GetValue<T>(string Key, T defaultValue) where T : IConvertible
{
if (ConfigOptions.TryGetValue(Key, out string? value)) {
try {
return (T)Convert.ChangeType(value, typeof(T));
} catch {
Console.WriteLine($"Config option {Key} is invalid, setting to default.");
}
}
SetValue(Key, defaultValue);
return defaultValue;
}
public string GetValue(string Key, string defaultValue)
{
if (ConfigOptions.TryGetValue(Key, out string? value)) {
return value;
}
SetValue(Key, defaultValue);
return defaultValue;
}
public void SetValue<T>(string Key, T Value) where T : IConvertible
{
string? ValueString = Value.ToString();
if (ValueString is null) return;
SetValue(Key, ValueString);
}
public void SetValue(string Key, string Value)
{
if (ConfigOptions.TryAdd(Key, Value)) {
OptionChanged = true;
} else if (ConfigOptions[Key] != Value) {
ConfigOptions[Key] = Value;
OptionChanged = true;
}
}
}
|