using System.Text; using System.Text.Json; namespace DevJsonDB.IO; public class LocalStore : IStore { private static Encoding DefaultEncoding = Encoding.UTF8; private string filePath; private List items; public LocalStore(string filePath) { this.filePath = filePath; this.items = new List(); this.InitDatabase(); } public void Dispose() { this.Commit(); } public void Commit() { try { using (FileStream fs = new FileStream(this.filePath, FileMode.OpenOrCreate)) using (StreamWriter writer = new StreamWriter(fs, DefaultEncoding)) { foreach (T item in this.items) { string json = JsonSerializer.Serialize(item); writer.WriteLine(json); } } } catch (Exception ex) { throw new JsonDBException(ex.Message, ex); } } public bool Add(T item) { if (this.items.Contains(item)) { return false; } this.items.Add(item); return true; } public IEnumerable GetValues() { return this.items.ToList(); } private void InitDatabase() { try { using (FileStream fs = new FileStream(this.filePath, FileMode.OpenOrCreate)) using (StreamReader reader = new StreamReader(fs, DefaultEncoding)) { string? line = null; while ((line = reader.ReadLine()) != null) { T? value = JsonSerializer.Deserialize(line); if (value is object) { this.items.Add(value); } } } } catch (Exception ex) { throw new JsonDBException(ex.Message, ex); } } }