我想制作一个dictionory对象的二进制序列化。
这是我的词典对象
public Dictionary<int, UserSessionInfo> UserSessionLookupTable = new Dictionary<int, UserSessionInfo>();
这是我的UserSessionInfo类
public class UserSessionInfo
{
public int SessionId { get; set; }
public string UserName { get; set; }
public Guid SessionGuid { get; set; }
public DateTime LoginTime { get; set; }
public bool IsActiveUser { get; set; }
public RowState State { get; set; }
}
这是我在用户登录时创建字典条目的方式
UserSessionLookupTable.Add(SessionId, userSessionInfoLogin);
现在我想二进制序列化UserSessionLookupTable对象。我该怎么做?
我试过了
var binFormatter = new BinaryFormatter();
var mStream = new MemoryStream();
binFormatter.Serialize(mStream, UserSessionLookupTable);
mStream.ToArray();
它会起作用吗?
如何在用户注销时从字典中删除条目?
答案 0 :(得分:5)
以下是使用标准.Net二进制序列化程序的扩展方法,也用于反序列化,压缩和解压缩它减少字节数组的大小:
public static class ObjectSerialize
{
public static byte[] Serialize(this Object obj)
{
if (obj == null)
{
return null;
}
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, obj);
var compressed = Compress(memoryStream.ToArray());
return compressed;
}
}
public static Object DeSerialize(this byte[] arrBytes)
{
using (var memoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
var decompressed = Decompress(arrBytes);
memoryStream.Write(decompressed, 0, decompressed.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memoryStream);
}
}
public static byte[] Compress(byte[] input)
{
byte[] compressesData;
using (var outputStream = new MemoryStream())
{
using (var zip = new GZipStream(outputStream, CompressionMode.Compress))
{
zip.Write(input, 0, input.Length);
}
compressesData = outputStream.ToArray();
}
return compressesData;
}
public static byte[] Decompress(byte[] input)
{
byte[] decompressedData;
using (var outputStream = new MemoryStream())
{
using (var inputStream = new MemoryStream(input))
{
using (var zip = new GZipStream(inputStream, CompressionMode.Decompress))
{
zip.CopyTo(outputStream);
}
}
decompressedData = outputStream.ToArray();
}
return decompressedData;
}
}
但我建议您使用ProtoBuf
进行二进制序列化,更多详情here
它可以像以下一样简单:
using ProtoBuf
var memoryStream = new MemoryStream();
// Serialize the Data to Stream
byte[] data = Serializer.Serialize(memoryStream, UserSessionLookupTable);
在这里你也可以包括上面建议的压缩和解压缩,根据我的经验,ProBuf比标准的Serialize快得多。
要修改字典中的任何内容,您需要deserialize
通过在标准序列化程序的情况下调用上面的方法:
var userSessionLookUpDeserialize =
(Dictionary<int,UserSessionInfo>)data.DeSerialize();
以下是ProtoBuf的代码:
var userSessionLookUpDeserialize = Serializer.Deserialize<Dictionary<int, UserSessionInfo>>(new MemoryStream(deCompresseBytes));
现在更改userSessionLookUpDeserialize