-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigHandler.cs
More file actions
89 lines (81 loc) · 2.48 KB
/
ConfigHandler.cs
File metadata and controls
89 lines (81 loc) · 2.48 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace FloatChat;
public class ConfigHandler {
public dynamic Data { get; private set; }
public string ConfigFilePath { get; private set; }
private readonly string appDataPath;
private readonly string configDirectoryPath;
private readonly Dictionary<string, dynamic> defaultSettings = new() {
{ "botToken", "" },
{ "channelId", 0 },
{ "nick", "" },
{ "processName", "" },
{ "alwaysShowInProcess", false },
{ "hideTimer", 10 },
{ "newMessageHideTimer", 10 },
{ "sizeX", 500 },
{ "sizeY", 250 },
{ "locationX", 25 },
{ "locationY", Screen.PrimaryScreen.Bounds.Bottom - 550 },
{ "activeOpacity", 0.75 },
{ "inactiveOpacity", 0.5 },
{ "chatBoxFont", "" },
{ "chatBoxFontSize", 15 },
{ "inputBoxFont", "" },
{ "inputBoxFontSize", 15 }
};
public ConfigHandler() {
appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
configDirectoryPath = Path.Join(appDataPath, Program.Name);
if (!Directory.Exists(configDirectoryPath)) {
Directory.CreateDirectory(configDirectoryPath);
}
ConfigFilePath = Path.Join(configDirectoryPath, "config.json");
if (!File.Exists(ConfigFilePath)) {
File.Create(ConfigFilePath).Dispose();
}
LoadConfig();
}
public void LoadConfig() {
try {
string configContent = File.ReadAllText(ConfigFilePath);
if (string.IsNullOrEmpty(configContent)) {
configContent = "{}";
}
Data = JObject.Parse(configContent);
bool save = false;
foreach (KeyValuePair<string, dynamic> setting in defaultSettings) {
if (Data[setting.Key] == null) {
save = true;
Data[setting.Key] = setting.Value;
}
}
if (save) {
SaveConfig();
}
} catch (Exception e) {
MessageBox.Show($"Failed to read the config file\n\n{e}", Program.Name);
Environment.Exit(1);
}
}
public void SaveConfig() {
try {
File.WriteAllText(ConfigFilePath, "");
using FileStream file = File.OpenWrite(ConfigFilePath);
using StreamWriter writer = new(file);
using JsonTextWriter jsonTextWriter = new(writer) {
Formatting = Formatting.Indented,
Indentation = 1,
IndentChar = '\t'
};
new JsonSerializer().Serialize(jsonTextWriter, Data);
} catch (Exception e) {
MessageBox.Show($"Failed to write to the config file\n\n{e}", Program.Name);
}
}
}