Files

77 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace StandardScene.Signal
{
/// <summary>
/// 信号插件 JSON 的路径解析与读写。
/// </summary>
/// <remarks>
/// 只使用 SimpleLite 工作目录 <c>Config/Signal/*.json</c>,不读、不拷 <c>plugins/Config/Signal</c>。
/// 文件不存在时 Load 返回空表;Save 会创建目录。
/// 迷毂数据中心走同一套文件;保存后需在本进程点「重新加载配置」。
/// 枚举按名字序列化(<see cref="StringEnumConverter"/>),与样例里 <c>"上线机构"</c> 一致。
/// </remarks>
public static class SignalConfigStore
{
/// <summary>保存时串行写盘,避免 CycleGUI 与迷毂 API 同时 Save 互相覆盖一半。</summary>
private static readonly object FileLock = new object();
private static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
Converters = { new StringEnumConverter() }
};
/// <summary>
/// 相对路径固定落到工作目录(SimpleLite.exe 所在目录)下的 <c>Config/Signal</c>。
/// 已是绝对路径则原样返回。文件不存在也返回该路径,不回退插件目录。
/// </summary>
public static string Resolve(string configuredPath)
{
if (string.IsNullOrWhiteSpace(configuredPath))
configuredPath = Path.Combine("Config", "Signal", "stations.json");
if (Path.IsPathRooted(configuredPath))
return configuredPath;
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configuredPath);
}
/// <summary>
/// 反序列化为列表。文件不存在、空、或 JSON 损坏时返回空列表,不抛给启动流程。
/// </summary>
public static List<T> Load<T>(string path) where T : class
{
try
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return new List<T>();
var json = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(json))
return new List<T>();
return JsonConvert.DeserializeObject<List<T>>(json, JsonSettings) ?? new List<T>();
}
catch
{
return new List<T>();
}
}
/// <summary>缩进写入;自动建目录。与 Load 共用枚举按名序列化。</summary>
public static void Save<T>(string path, IReadOnlyList<T> items)
{
var json = JsonConvert.SerializeObject(items ?? Array.Empty<T>(), JsonSettings);
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
lock (FileLock)
File.WriteAllText(path, json);
}
}
}