80 lines
2.2 KiB
C#
80 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Web.Script.Serialization;
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
namespace AnotherReplayReader
|
|
{
|
|
internal sealed class Cache
|
|
{
|
|
public static string CacheDirectory => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RA3Bar.Lanyi.AnotherReplayReader");
|
|
public static string CacheFilePath => Path.Combine(CacheDirectory, "AnotherReplayReader.cache");
|
|
|
|
private ConcurrentDictionary<string, string> _storage;
|
|
|
|
public Cache()
|
|
{
|
|
try
|
|
{
|
|
if (!Directory.Exists(CacheDirectory))
|
|
{
|
|
Directory.CreateDirectory(CacheDirectory);
|
|
}
|
|
|
|
var serializer = new JavaScriptSerializer();
|
|
_storage = serializer.Deserialize<ConcurrentDictionary<string, string>>(File.ReadAllText(CacheFilePath));
|
|
}
|
|
catch
|
|
{
|
|
_storage = new ConcurrentDictionary<string, string>();
|
|
}
|
|
}
|
|
|
|
public T GetOrDefault<T>(string key, in T defaultValue)
|
|
{
|
|
try
|
|
{
|
|
if (_storage.TryGetValue(key, out var valueString))
|
|
{
|
|
var serializer = new JavaScriptSerializer();
|
|
return serializer.Deserialize<T>(valueString);
|
|
}
|
|
}
|
|
catch { }
|
|
return defaultValue;
|
|
}
|
|
|
|
public void Set<T>(string key, in T value)
|
|
{
|
|
try
|
|
{
|
|
var serializer = new JavaScriptSerializer();
|
|
_storage[key] = serializer.Serialize(value);
|
|
Save();
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
public void Remove(string key)
|
|
{
|
|
_storage.TryRemove(key, out _);
|
|
Save();
|
|
}
|
|
|
|
public void Save()
|
|
{
|
|
try
|
|
{
|
|
var serializer = new JavaScriptSerializer();
|
|
File.WriteAllText(CacheFilePath, serializer.Serialize(_storage));
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
}
|