104 lines
3.4 KiB
C#
104 lines
3.4 KiB
C#
using System;
|
|
using System.IO;
|
|
using Newtonsoft.Json;
|
|
using Logger;
|
|
|
|
namespace UIShare.GlobalVariable
|
|
{
|
|
public static class ConfigService
|
|
{
|
|
private static readonly object _fileLock = new();
|
|
/// <summary>
|
|
/// 根据标题查询配置文件是否存在
|
|
/// </summary>
|
|
public static bool IsExit(string title)
|
|
{
|
|
if (string.IsNullOrEmpty(title))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// 临时实例化一个对象以获取默认的 SystemPath
|
|
var dummy = new SystemConfig();
|
|
string configPath = Path.Combine(dummy.SystemPath, $"{title}.json");
|
|
|
|
if (!File.Exists(configPath))
|
|
{
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
/// <summary>
|
|
/// 根据标题(格子标识)加载独立的配置文件
|
|
/// </summary>
|
|
public static SystemConfig Load(string title)
|
|
{
|
|
if (string.IsNullOrEmpty(title))
|
|
{
|
|
throw new ArgumentException("配置标题不能为空", nameof(title));
|
|
}
|
|
|
|
// 临时实例化一个对象以获取默认的 SystemPath
|
|
var dummy = new SystemConfig();
|
|
string configPath = Path.Combine(dummy.SystemPath, $"{title}.json");
|
|
|
|
if (!File.Exists(configPath))
|
|
{
|
|
// 如果不存在,创建一个带 Title 的默认配置并保存
|
|
var defaultConfig = new SystemConfig { Title = title };
|
|
Save(defaultConfig);
|
|
return defaultConfig;
|
|
}
|
|
|
|
lock (_fileLock)
|
|
{
|
|
try
|
|
{
|
|
string json = File.ReadAllText(configPath);
|
|
var config = JsonConvert.DeserializeObject<SystemConfig>(json, new JsonSerializerSettings
|
|
{
|
|
TypeNameHandling = TypeNameHandling.All
|
|
});
|
|
|
|
return config ?? new SystemConfig { Title = title };
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LoggerHelper.ErrorWithNotify($"格子 [{title}] 配置加载失败: {ex.Message}");
|
|
return new SystemConfig { Title = title };
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 保存指定的配置实例
|
|
/// </summary>
|
|
public static void Save(SystemConfig config)
|
|
{
|
|
if (config == null || string.IsNullOrEmpty(config.Title)) return;
|
|
|
|
lock (_fileLock)
|
|
{
|
|
try
|
|
{
|
|
if (!Directory.Exists(config.SystemPath))
|
|
Directory.CreateDirectory(config.SystemPath);
|
|
|
|
string configPath = Path.Combine(config.SystemPath, $"{config.Title}.json");
|
|
|
|
string json = JsonConvert.SerializeObject(config, Formatting.Indented, new JsonSerializerSettings
|
|
{
|
|
TypeNameHandling = TypeNameHandling.All
|
|
});
|
|
|
|
File.WriteAllText(configPath, json);
|
|
LoggerHelper.InfoWithNotify($"配置 [{config.Title}] 已保存。");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LoggerHelper.ErrorWithNotify($"配置 [{config.Title}] 保存失败: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} |