JsonHandler.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Text.Json;
  7. using System.Text.Json.Serialization.Metadata;
  8. namespace crusherScanner
  9. {
  10. internal class JsonHandler
  11. {
  12. private string filePath;
  13. private bool isSettingsFile;
  14. public Settings settings;
  15. public List<Logs>? log;
  16. /// <summary>
  17. /// Open or create a JSON file.
  18. /// </summary>
  19. /// <param name="filePath">Path to where the file is located or should be created.</param>
  20. /// <param name="isSettingsfile">Is this a settings file? or a log file.</param>
  21. public JsonHandler(string filePath,bool isSettingsfile)
  22. {
  23. this.filePath = filePath;
  24. this.isSettingsFile = isSettingsfile;
  25. if (isSettingsfile)
  26. {
  27. if (File.Exists(filePath))
  28. {
  29. string fileData = File.ReadAllText(filePath);
  30. settings = JsonSerializer.Deserialize<Settings>(fileData);
  31. }
  32. else
  33. {
  34. settings = new Settings();
  35. }
  36. }
  37. else
  38. {
  39. if (File.Exists(filePath))
  40. {
  41. string fileData = File.ReadAllText(filePath);
  42. log = JsonSerializer.Deserialize<List<Logs>>(fileData);
  43. }
  44. else
  45. {
  46. log = new List<Logs>();
  47. }
  48. }
  49. }
  50. public void Save()
  51. {
  52. string fileData;
  53. if (isSettingsFile)
  54. {
  55. fileData = JsonSerializer.Serialize(settings);
  56. }
  57. else
  58. {
  59. fileData = JsonSerializer.Serialize(log);
  60. }
  61. File.WriteAllText(filePath, fileData);
  62. }
  63. }
  64. }