BOB/ProcessManager/JsonHelper.cs
2025-11-19 11:33:56 +08:00

62 lines
1.8 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");
public static string ConfigFile;
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))
{
throw new Exception("没找到系统配置文件");
}
try
{
string json = File.ReadAllText(ConfigFile);
return JsonConvert.DeserializeObject<SystemConfig>(json, jsonSettings);
}
catch (Exception ex)
{
// 如果反序列化失败,避免程序崩溃
throw new Exception("系统配置加载失败: " + ex.Message);
}
}
}
#endregion
}
}