using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Muchinfo.PC.Common.Bosn
{
public class BsonHelper
{
///
/// Loads the data.
///
///
/// The file path.
/// List{``0}.
public static List LoadData(string filePath)
{
var result = new List();
if (!File.Exists(filePath)) return result;
try
{
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
using (var memory = new MemoryStream())
{
ZipHelper.Decompress(stream, memory);
using (var reader = new BsonReader(memory))
{
//反序列化集合必须设置此值
reader.ReadRootValueAsArray = true;
var serializer = new JsonSerializer();
result = serializer.Deserialize>(reader).ToList();
}
}
}
return result;
}
catch
{
return null;
}
}
///
/// Saves the data.
///
///
/// The file path.
/// The source.
/// The comparer.
/// if set to true [is override].
public static void SaveData(string filePath, T source, IEqualityComparer comparer, bool isOverride = false)
{
if (null == source) return;
var list = new List() { source };
SaveData(filePath, list, comparer, isOverride);
}
///
/// Saves the data.
///
///
/// The file path.
/// The list.
/// The comparer.
/// if set to true [is override].
public static void SaveData(string filePath, List list, IEqualityComparer comparer, bool isOverride = false)
{
if (null == list) return;
var folderPath = Path.GetDirectoryName(filePath);
if (string.IsNullOrWhiteSpace(folderPath)) return;
if (!Directory.Exists(folderPath)) Directory.CreateDirectory(folderPath);
List data;
if (isOverride && File.Exists(filePath))
{
File.Delete(filePath);
data = list;
}
else
{
data = LoadData(filePath) ?? new List();
data = list.Union(data, comparer).ToList();
}
using (var stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
using (var memory = new MemoryStream())
{
using (var writer = new BsonWriter(memory))
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var serializer = JsonSerializer.Create(settings);
serializer.Formatting = Formatting.None;
serializer.Serialize(writer, data);
memory.Seek(0, SeekOrigin.Begin);
ZipHelper.Compress(memory, stream);
}
}
}
}
}
}