65 lines
2.0 KiB
C#
65 lines
2.0 KiB
C#
using BOB;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.IO;
|
|
|
|
namespace ProcessManager
|
|
{
|
|
public class JsonHelper
|
|
{
|
|
private static readonly object _lock = new();
|
|
public static string SystemPath { get; set; } =
|
|
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BOB");
|
|
|
|
private static string ConfigFile => Path.Combine(SystemPath, "system.json");
|
|
|
|
private static readonly JsonSerializerSettings jsonSettings = new()
|
|
{
|
|
TypeNameHandling = TypeNameHandling.All, // 必须开启
|
|
Formatting = Formatting.Indented,
|
|
MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
|
|
};
|
|
|
|
#region 配置保存
|
|
public static void SaveToFile(SystemConfig config)
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (!Directory.Exists(SystemPath))
|
|
Directory.CreateDirectory(SystemPath);
|
|
|
|
string json = JsonConvert.SerializeObject(config, jsonSettings);
|
|
File.WriteAllText(ConfigFile, json);
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region 配置加载
|
|
public static SystemConfig LoadFromFile()
|
|
{
|
|
lock (_lock)
|
|
{
|
|
if (!File.Exists(ConfigFile))
|
|
{
|
|
// 如果不存在自动创建一个默认的 SystemConfig
|
|
var defaultConfig = new SystemConfig();
|
|
SaveToFile(defaultConfig);
|
|
return defaultConfig;
|
|
}
|
|
|
|
try
|
|
{
|
|
string json = File.ReadAllText(ConfigFile);
|
|
return JsonConvert.DeserializeObject<SystemConfig>(json, jsonSettings);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// 如果反序列化失败,避免程序崩溃
|
|
throw new Exception("系统配置加载失败: " + ex.Message);
|
|
}
|
|
}
|
|
}
|
|
#endregion
|
|
}
|
|
}
|