添加项目文件。
This commit is contained in:
85
UIShare/GlobalVariable/ConfigService.cs
Normal file
85
UIShare/GlobalVariable/ConfigService.cs
Normal file
@@ -0,0 +1,85 @@
|
||||
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 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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user