using System.IO; using Newtonsoft.Json; namespace SHH.CameraDashboard.Services { public static class StorageService { // 基础目录:C:\Users\Name\AppData\Local\SHH_Dashboard\ private static readonly string BaseDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SHH_CameraDashboard"); /// /// 泛型保存:将数据 T 序列化为指定文件名的 JSON /// public static void Save(T data, string fileName) where T : class { try { if (!Directory.Exists(BaseDir)) Directory.CreateDirectory(BaseDir); string filePath = Path.Combine(BaseDir, fileName); string json = JsonConvert.SerializeObject(data, Formatting.Indented); File.WriteAllText(filePath, json); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"存储失败 [{fileName}]: {ex.Message}"); } } /// /// 泛型读取:从指定 JSON 文件反序列化为数据 T /// public static T Load(string fileName) where T : class, new() { try { string filePath = Path.Combine(BaseDir, fileName); if (!File.Exists(filePath)) return new T(); string json = File.ReadAllText(filePath); return JsonConvert.DeserializeObject(json) ?? new T(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"读取失败 [{fileName}]: {ex.Message}"); return new T(); } } } }