SaveLoadService.cs 913 B

123456789101112131415161718192021222324252627282930
  1. using Bmp.Core.Common.AssemblyInject.Interfaces;
  2. using Bmp.Core.Common.EventBus;
  3. using Bmp.WinForms.SaveLoad.Models;
  4. using Newtonsoft.Json;
  5. namespace Bmp.WinForms.SaveLoad;
  6. internal class SaveLoadService : IAssemblyInjectSingleton, IAssemblyInjectSyncInitStarStop
  7. {
  8. private readonly IEventBus _eventBus;
  9. private static readonly string FileName = $"{Application.ExecutablePath}.{nameof(SaveLoadState)}.json";
  10. public SaveLoadState State { get; private set; } = new();
  11. public SaveLoadService(IEventBus eventBus) => _eventBus = eventBus;
  12. public void Init()
  13. {
  14. }
  15. public void Start()
  16. {
  17. if (File.Exists(FileName)) State = JsonConvert.DeserializeObject<SaveLoadState>(File.ReadAllText(FileName)) ?? new();
  18. else State = new();
  19. }
  20. public void Stop() => Save();
  21. public void Save() => File.WriteAllText(FileName, JsonConvert.SerializeObject(State));
  22. }