using System; using System.Collections.Generic; using System.IO; using System.Threading; using Newtonsoft.Json; namespace Helpers { public class JsonPersistentStore<T> { private readonly string FileName; private readonly SemaphoreSlim Semaphore = new SemaphoreSlim(1, 1); public readonly List<T> Items = new List<T>(); public JsonPersistentStore(string fileName) { FileName = fileName; } public void Load() { if (!File.Exists(FileName)) return; var json = File.ReadAllText(FileName); try { Items.AddRange(JsonConvert.DeserializeObject<IEnumerable<T>>(json)); } catch (Exception ex) { DomainPorts.Logger.Warning($"Failed to load items from file: {FileName}", ex); } } public void Save() { Semaphore.Wait(); try { var json = JsonConvert.SerializeObject(Items); File.WriteAllText(FileName, json); } catch (Exception ex) { DomainPorts.Logger.Warning($"Failed to save items to file: {FileName}", ex); } finally { Semaphore.Release(); } } } }
688700cookie-checkC# Simple Json Persistent Store