Skip to content

Instantly share code, notes, and snippets.

@hanssens
Created June 10, 2016 10:19
Show Gist options
  • Save hanssens/53f20ba96a70060b195fb36f81af4317 to your computer and use it in GitHub Desktop.
Save hanssens/53f20ba96a70060b195fb36f81af4317 to your computer and use it in GitHub Desktop.
Poor man's example of read/write of objects to a file, let's call it "cache", using JSON serialize/deserialize. Note that this stores the file hardcoded in ~/Data/APPNAME.cache.
[Serializable]
public static class CacheProvider
{
public const string CacheFilename = "APPNAME.cache";
public static string DataStoragePath()
{
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
}
/// <summary>
/// Persist the cache to filesystem.
/// </summary>
public static void Flush<T>(T instance) where T : class
{
var raw = JsonConvert.SerializeObject(instance);
var cacheFile = Path.Combine(DataStoragePath(), CacheFilename);
File.WriteAllText(cacheFile, raw);
}
/// <summary>
/// Attempts to load the cache from filesystem, or returns null if not available.
/// </summary>
public static T Load<T>() where T : class, new()
{
try
{
var cacheFile = Path.Combine(DataStoragePath(), CacheFilename);
var raw = File.ReadAllText(cacheFile);
return JsonConvert.DeserializeObject<T>(raw);
}
catch (Exception)
{
return new T();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment