-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettings.cs
More file actions
96 lines (86 loc) · 2.8 KB
/
Copy pathSettings.cs
File metadata and controls
96 lines (86 loc) · 2.8 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
90
91
92
93
94
95
96
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using MtkClient.Library.Utils;
namespace MtkClient.Library
{
public class Settings : LogBase
{
private readonly string _settingsPath;
private Dictionary<string, object> _settings;
public Settings(string settingsPath = null, LogLevel logLevel = LogLevel.Info)
{
InitLogger(logLevel);
_settingsPath = settingsPath ?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".mtkclient", "settings.json"
);
_settings = new Dictionary<string, object>();
Load();
}
public void Load()
{
try
{
if (File.Exists(_settingsPath))
{
var json = File.ReadAllText(_settingsPath);
_settings = JsonConvert.DeserializeObject<Dictionary<string, object>>(json)
?? new Dictionary<string, object>();
Debug($"Settings loaded from {_settingsPath}");
}
}
catch (Exception ex)
{
Warning($"Failed to load settings: {ex.Message}");
_settings = new Dictionary<string, object>();
}
}
public void Save()
{
try
{
var dir = Path.GetDirectoryName(_settingsPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
var json = JsonConvert.SerializeObject(_settings, Formatting.Indented);
File.WriteAllText(_settingsPath, json);
Debug($"Settings saved to {_settingsPath}");
}
catch (Exception ex)
{
Error($"Failed to save settings: {ex.Message}");
}
}
public T Get<T>(string key, T defaultValue = default)
{
if (_settings.TryGetValue(key, out var value))
{
try
{
if (value is T typed) return typed;
return (T)Convert.ChangeType(value, typeof(T));
}
catch { return defaultValue; }
}
return defaultValue;
}
public void Set(string key, object value)
{
_settings[key] = value;
}
public bool Has(string key)
{
return _settings.ContainsKey(key);
}
public void Remove(string key)
{
_settings.Remove(key);
}
public Dictionary<string, object> GetAll()
{
return new Dictionary<string, object>(_settings);
}
}
}