SettingsService.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.IO;
  3. using System.Text.Json;
  4. using SlamCross.Models;
  5. namespace SlamCross.Services;
  6. public class SettingsService
  7. {
  8. private static readonly string SettingsPath = Path.Combine(
  9. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  10. "SLAM", "settings.json");
  11. public AppSettings Settings { get; private set; } = new();
  12. public void Load()
  13. {
  14. try
  15. {
  16. if (File.Exists(SettingsPath))
  17. {
  18. var json = File.ReadAllText(SettingsPath);
  19. Settings = JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
  20. }
  21. }
  22. catch
  23. {
  24. Settings = new AppSettings();
  25. }
  26. }
  27. public void Save()
  28. {
  29. try
  30. {
  31. Directory.CreateDirectory(Path.GetDirectoryName(SettingsPath)!);
  32. var json = JsonSerializer.Serialize(Settings, new JsonSerializerOptions { WriteIndented = true });
  33. File.WriteAllText(SettingsPath, json);
  34. }
  35. catch { }
  36. }
  37. }