Persistence.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using LC.Newtonsoft.Json;
  6. using TapTap.Common;
  7. namespace TapTap.AntiAddiction.Internal
  8. {
  9. /// <summary>
  10. /// 通用 JSON 序列化工具
  11. /// </summary>
  12. internal class Persistence
  13. {
  14. private readonly string _filePath;
  15. internal Persistence(string path)
  16. {
  17. _filePath = path;
  18. }
  19. internal async Task<T> Load<T>() where T : class
  20. {
  21. TapLogger.Debug(_filePath);
  22. if (!File.Exists(_filePath))
  23. {
  24. return null;
  25. }
  26. string text;
  27. using (FileStream fs = File.OpenRead(_filePath))
  28. {
  29. byte[] buffer = new byte[fs.Length];
  30. await fs.ReadAsync(buffer, 0, (int)fs.Length);
  31. text = Encoding.UTF8.GetString(buffer);
  32. }
  33. try
  34. {
  35. return JsonConvert.DeserializeObject<T>(text);
  36. }
  37. catch (Exception e)
  38. {
  39. TapLogger.Error(e);
  40. Delete();
  41. return null;
  42. }
  43. }
  44. internal async Task Save<T>(T obj)
  45. {
  46. if (obj == null)
  47. {
  48. TapLogger.Error("Saved object is null.");
  49. return;
  50. }
  51. string text;
  52. try
  53. {
  54. text = JsonConvert.SerializeObject(obj);
  55. }
  56. catch (Exception e)
  57. {
  58. TapLogger.Error(e);
  59. return;
  60. }
  61. string dirPath = Path.GetDirectoryName(_filePath);
  62. if (!string.IsNullOrEmpty(dirPath) && !Directory.Exists(dirPath))
  63. {
  64. Directory.CreateDirectory(dirPath);
  65. }
  66. using (FileStream fs = File.Create(_filePath))
  67. {
  68. byte[] buffer = Encoding.UTF8.GetBytes(text);
  69. await fs.WriteAsync(buffer, 0, buffer.Length);
  70. }
  71. }
  72. internal void Delete()
  73. {
  74. if (!File.Exists(_filePath))
  75. {
  76. return;
  77. }
  78. File.Delete(_filePath);
  79. }
  80. }
  81. }