PowerToys/Wox.Infrastructure/Storage/BinaryStorage.cs

118 lines
3.8 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using Wox.Infrastructure.Logger;
namespace Wox.Infrastructure.Storage
{
/// <summary>
/// Stroage object using binary data
/// Normally, it has better performance, but not readable
/// </summary>
public class BinaryStorage<T>
{
public BinaryStorage(string filename)
{
const string directoryName = "Cache";
var directoryPath = Path.Combine(Constant.DataDirectory, directoryName);
Helper.ValidateDirectory(directoryPath);
const string fileSuffix = ".cache";
FilePath = Path.Combine(directoryPath, $"{filename}{fileSuffix}");
}
public string FilePath { get; }
public T TryLoad(T defaultData)
{
if (File.Exists(FilePath))
{
using (var stream = new FileStream(FilePath, FileMode.Open))
{
if (stream.Length > 0)
{
var d = Deserialize(stream, defaultData);
return d;
2015-01-06 18:28:23 +08:00
}
else
{
2017-01-24 08:24:20 +08:00
Log.Error($"|BinaryStorage.TryLoad|Zero length cache file <{FilePath}>");
Save(defaultData);
return defaultData;
}
}
}
else
{
2017-01-24 08:24:20 +08:00
Log.Info("|BinaryStorage.TryLoad|Cache file not exist, load default data");
Save(defaultData);
return defaultData;
}
}
private T Deserialize(FileStream stream, T defaultData)
{
//http://stackoverflow.com/questions/2120055/binaryformatter-deserialize-gives-serializationexception
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
BinaryFormatter binaryFormatter = new BinaryFormatter
{
AssemblyFormat = FormatterAssemblyStyle.Simple
};
try
{
2017-01-24 08:24:20 +08:00
var t = (T)binaryFormatter.Deserialize(stream);
return t;
}
2016-08-20 08:02:20 +08:00
catch (System.Exception e)
{
2017-01-24 08:24:20 +08:00
Log.Exception($"|BinaryStorage.Deserialize|Deserialize error for file <{FilePath}>", e);
return defaultData;
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
}
}
2016-01-07 05:34:42 +08:00
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly ayResult = null;
string sShortAssemblyName = args.Name.Split(',')[0];
Assembly[] ayAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ayAssembly in ayAssemblies)
{
if (sShortAssemblyName == ayAssembly.FullName.Split(',')[0])
{
ayResult = ayAssembly;
break;
}
}
return ayResult;
}
public void Save(T data)
{
using (var stream = new FileStream(FilePath, FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter
{
AssemblyFormat = FormatterAssemblyStyle.Simple
};
try
{
binaryFormatter.Serialize(stream, data);
}
catch (SerializationException e)
{
2017-01-24 08:24:20 +08:00
Log.Exception($"|BinaryStorage.Save|serialize error for file <{FilePath}>", e);
2015-01-23 21:52:46 +08:00
}
}
}
}
}