| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- 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) || !File.Exists(filePath))
- return false;
- using StreamReader sr = new(filePath);
- try
- {
- string jsonContent = sr.ReadToEnd();
- output = JsonSerializer.Deserialize<T>(jsonContent);
- }
- catch
- {
- return false;
- }
- return true;
- }
- public static bool WriteFile<T>(string filePath, T input)
- {
- if (input is null || string.IsNullOrEmpty(filePath))
- return false;
- try
- {
- FileInfo file = new(filePath);
- if (file.Directory is not DirectoryInfo directory)
- return false;
- if (!Directory.Exists(directory.FullName))
- Directory.CreateDirectory(directory.FullName);
- string jsonContent = JsonSerializer.Serialize(input);
- using StreamWriter sw = new(filePath, false);
- sw.WriteLine(jsonContent);
- }
- catch
- {
- return false;
- }
- return true;
- }
- }
|