JsonHelper.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Text.Json;
  2. namespace Universal;
  3. public class JsonHelper
  4. {
  5. public static bool ReadFile<T>(string filePath, out T? output)
  6. {
  7. output = default;
  8. if (string.IsNullOrEmpty(filePath))
  9. return false;
  10. if (!File.Exists(filePath))
  11. return false;
  12. try
  13. {
  14. using StreamReader sr = new(filePath);
  15. XmlSerializer xz = new(typeof(T));
  16. string json = sr.ReadToEnd();
  17. T? temp = JsonSerializer.Deserialize<T>(json);
  18. if (temp is null)
  19. return false;
  20. output = temp;
  21. }
  22. catch
  23. {
  24. return false;
  25. }
  26. return true;
  27. }
  28. public static bool WriteFile(string filePath, object input)
  29. {
  30. if (input == null)
  31. return false;
  32. if (string.IsNullOrEmpty(filePath))
  33. return false;
  34. try
  35. {
  36. FileInfo file = new(filePath);
  37. if (!Directory.Exists(file.Directory!.FullName))
  38. Directory.CreateDirectory(file.Directory!.FullName);
  39. using StreamWriter sw = file.CreateText();
  40. sw.Write(JsonSerializer.Serialize(input));
  41. }
  42. catch
  43. {
  44. return false;
  45. }
  46. return true;
  47. }
  48. }