12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- using System.Text.Json;
- namespace Universal;
- public class JsonHelper
- {
- public static bool ReadFile<T>(string filePath, out T? output)
- {
- output = default;
- if (string.IsNullOrEmpty(filePath))
- return false;
- if (!File.Exists(filePath))
- return false;
- try
- {
- using StreamReader sr = new(filePath);
- XmlSerializer xz = new(typeof(T));
- string json = sr.ReadToEnd();
- T? temp = JsonSerializer.Deserialize<T>(json);
- if (temp is null)
- return false;
- output = temp;
- }
- catch
- {
- return false;
- }
- return true;
- }
- public static bool WriteFile(string filePath, object input)
- {
- if (input == null)
- return false;
- if (string.IsNullOrEmpty(filePath))
- return false;
- try
- {
- FileInfo file = new(filePath);
- if (!Directory.Exists(file.Directory!.FullName))
- Directory.CreateDirectory(file.Directory!.FullName);
- using StreamWriter sw = file.CreateText();
- sw.Write(JsonSerializer.Serialize(input));
- }
- catch
- {
- return false;
- }
- return true;
- }
- }
|