Skip to content

Instantly share code, notes, and snippets.

@hesenger
Created July 17, 2019 18:41
Show Gist options
  • Save hesenger/7eea8d2be41791636f2dfe969c62614b to your computer and use it in GitHub Desktop.
Save hesenger/7eea8d2be41791636f2dfe969c62614b to your computer and use it in GitHub Desktop.
AutoPersist
public class AutoPersist<T> : IEnumerable<T>
{
private readonly object _lock = new object();
private readonly List<T> _list;
private readonly string _path;
public AutoPersist()
{
_path = FormatPath();
if (File.Exists(_path))
{
var content = File.ReadAllText(_path);
_list = JsonConvert.DeserializeObject<List<T>>(content);
}
else
{
_list = new List<T>();
}
}
public int Count => _list.Count;
public virtual void Add(T obj)
{
_list.Add(obj);
Persist();
}
public virtual void Remove(T obj)
{
_list.Remove(obj);
Persist();
}
protected virtual void Persist()
{
lock (_lock)
{
File.WriteAllText(_path, JsonConvert.SerializeObject(_list));
}
}
protected virtual string FormatPath()
{
var path = HttpContext.Current == null
? "persist"
: HttpContext.Current.Server.MapPath("~/persist");
Directory.CreateDirectory(path);
return Path.Combine(path, typeof(T).Name + ".json");
}
public virtual IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment