JsonHelper.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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) || !File.Exists(filePath))
  9. return false;
  10. using StreamReader sr = new(filePath);
  11. try
  12. {
  13. string jsonContent = sr.ReadToEnd();
  14. output = JsonSerializer.Deserialize<T>(jsonContent);
  15. }
  16. catch
  17. {
  18. return false;
  19. }
  20. return true;
  21. }
  22. public static bool WriteFile<T>(string filePath, T input)
  23. {
  24. if (input is null || string.IsNullOrEmpty(filePath))
  25. return false;
  26. try
  27. {
  28. FileInfo file = new(filePath);
  29. if (file.Directory is not DirectoryInfo directory)
  30. return false;
  31. if (!Directory.Exists(directory.FullName))
  32. Directory.CreateDirectory(directory.FullName);
  33. string jsonContent = JsonSerializer.Serialize(input);
  34. using StreamWriter sw = new(filePath, false);
  35. sw.WriteLine(jsonContent);
  36. }
  37. catch
  38. {
  39. return false;
  40. }
  41. return true;
  42. }
  43. }