feat: 添加配置文件管理功能
This commit is contained in:
82
JackCraft.Config/Config.cs
Normal file
82
JackCraft.Config/Config.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace JackCraft.Config;
|
||||
|
||||
public class Config
|
||||
{
|
||||
private readonly FileInfo _configFile;
|
||||
public readonly string ConfigFileName;
|
||||
public readonly string ConfigFilePath;
|
||||
private Dictionary<string, object> _configData = null!;
|
||||
|
||||
public Config(FileInfo configFile)
|
||||
{
|
||||
_configFile = configFile;
|
||||
ConfigFilePath = configFile.DirectoryName ?? string.Empty;
|
||||
ConfigFileName = configFile.Name;
|
||||
if (!configFile.Exists)
|
||||
{
|
||||
configFile.Directory?.Create();
|
||||
using var stream = configFile.Create();
|
||||
File.WriteAllText(configFile.FullName, "{}");
|
||||
}
|
||||
|
||||
LoadConfigData();
|
||||
}
|
||||
|
||||
private void LoadConfigData()
|
||||
{
|
||||
if (File.Exists(_configFile.FullName))
|
||||
{
|
||||
var existingJson = File.ReadAllText(_configFile.FullName);
|
||||
_configData = JsonConvert.DeserializeObject<Dictionary<string, object>>(existingJson) ??
|
||||
new Dictionary<string, object>();
|
||||
}
|
||||
else
|
||||
{
|
||||
_configData = new Dictionary<string, object>();
|
||||
}
|
||||
}
|
||||
|
||||
public T? Get<T>(string key, T? defaultValue)
|
||||
{
|
||||
var keys = key.Split('.');
|
||||
var currentData = _configData;
|
||||
for (var i = 0; i < keys.Length - 1; i++)
|
||||
{
|
||||
if (!currentData.TryGetValue(keys[i], out var tValue)) return defaultValue;
|
||||
if (tValue is JObject jObject)
|
||||
currentData = jObject.ToObject<Dictionary<string, object>>();
|
||||
else if (tValue is Dictionary<string, object> nestedDict)
|
||||
currentData = nestedDict;
|
||||
else
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
if (currentData.TryGetValue(keys[^1], out var result) && result is T typedResult) return typedResult;
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public void Set<T>(string key, T? value)
|
||||
{
|
||||
var keys = key.Split('.');
|
||||
var currentData = _configData;
|
||||
for (var i = 0; i < keys.Length - 1; i++)
|
||||
{
|
||||
if (!currentData.TryGetValue(keys[i], out var tValue) ||
|
||||
tValue is not Dictionary<string, object> nestedDict)
|
||||
{
|
||||
nestedDict = new Dictionary<string, object>();
|
||||
currentData[keys[i]] = nestedDict;
|
||||
}
|
||||
|
||||
currentData = nestedDict;
|
||||
}
|
||||
|
||||
currentData[keys[^1]] = (object?)value ?? string.Empty;
|
||||
var json = JsonConvert.SerializeObject(_configData, Formatting.Indented);
|
||||
File.WriteAllText(_configFile.FullName, json);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user