Skip to content

Instantly share code, notes, and snippets.

@tonyedwardspz
Created August 20, 2024 20:28
Show Gist options
  • Save tonyedwardspz/6ce13cb2a51d6dcce641fc0d3999b539 to your computer and use it in GitHub Desktop.
Save tonyedwardspz/6ce13cb2a51d6dcce641fc0d3999b539 to your computer and use it in GitHub Desktop.
A quick data service to save in memory things to json files
using System.Diagnostics;
using System.Text.Json;
using MyNamespce.Models;
namespace MyNamespce.Services;
public class Data
{
private static readonly string _dataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "PodPod", "Data");
public static List<Podcast> Podcasts { get; set; }
private Data(){}
public static void init(){
Data.Podcasts = new List<Podcast>();
}
public static bool SaveFileExists(string fileName)
{
string filePath = Path.Combine(_dataFolder, $"{fileName}.json");
return File.Exists(filePath);
}
public static void SaveToJsonFile<T>(T data, string fileName)
{
Debug.WriteLine("Saving to file");
if (!Directory.Exists(_dataFolder))
{
Directory.CreateDirectory(_dataFolder);
}
try {
string filePath = Path.Combine(_dataFolder, $"{fileName}.json");
string json = JsonSerializer.Serialize(data);
File.WriteAllText(filePath, json);
Debug.WriteLine("Saved to file");
} catch (Exception e){
Console.WriteLine(e.Message);
Debug.WriteLine("Failed to save to file");
}
}
public static T LoadFromJsonFile<T>(string fileName)
{
string filePath = Path.Combine(_dataFolder, $"{fileName}.json");
if (File.Exists(filePath)){
try {
string json = File.ReadAllText(filePath);
return JsonSerializer.Deserialize<T>(json);
}catch (Exception e){
Console.WriteLine(e.Message);
}
}
return default;
}
}
@tonyedwardspz
Copy link
Author

Init your data service on app load

Data.Init()

Load saved data into the service :

Data.Podcasts = Data.LoadFromJsonFile<List<Podcast>>("podcasts");

Reference this loaded data around the app as you would any other c# list. Call the save method when appropriate.

Data.SaveToJsonFile(Data.Podcasts, "podcasts");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment