Skip to content

Instantly share code, notes, and snippets.

@Platonenkov
Last active May 27, 2021 07:36
Show Gist options
  • Save Platonenkov/fad472468c8b4b9e0a6ab8f96a49ff70 to your computer and use it in GitHub Desktop.
Save Platonenkov/fad472468c8b4b9e0a6ab8f96a49ff70 to your computer and use it in GitHub Desktop.
Save data to Json format
public static class JsonInFile
{
/// <summary>
/// Сохранение данных в файл
/// </summary>
public static async Task<bool> SaveToFileAsync<T>(string FilePath, T data)
{
try
{
using var file = File.Create(FilePath);
await JsonSerializer.SerializeAsync(file, data);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary> загрузка данных из файла </summary>
public static async Task<T> LoadFromFile<T>(string FilePath)
{
if (!File.Exists(FilePath)) return default;
try
{
using var file = File.OpenRead(FilePath);
return await JsonSerializer.DeserializeAsync<T>(file);
}
catch (Exception)
{
return default;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment