protobuf-net是Google的ProtocolBuffer的.net实现。ProtocolBuffer是用于结构化数据串行化的灵活、高效、自动的方法,有如XML,不过它更小、更快、也更简单。你可以定义自己的数据结构,然后使用代码生成器生成的代码来读写这个数据结构。你甚至可以在无需重新部署程序的情况下更新数据结构。
public class ProtobufDemo
{
static string abcStr = "buvcfgahopqidejwxrstyklmnz";
/// <summary>
/// 加密序列化
/// </summary>
/// <param name="obj">要序列化的对象</param>
/// <param name="path">保存路径</param>
/// <returns></returns>
public static void GeneralSerialize<T>(T obj, string path)
{
using (var fileStream = File.Create(path))
{
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes(abcStr[6].ToString() + abcStr[0].ToString() + abcStr[17].ToString() + abcStr[10].ToString() + abcStr[20].ToString() + abcStr[8].ToString() + abcStr[4].ToString() + abcStr[12].ToString());
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(abcStr[16].ToString() + abcStr[10].ToString() + abcStr[7].ToString() + abcStr[1].ToString() + abcStr[2].ToString() + abcStr[18].ToString() + abcStr[14].ToString() + abcStr[21].ToString());
CryptoStream crStream = new CryptoStream(fileStream, cryptic.CreateEncryptor(), CryptoStreamMode.Write);
Serializer.Serialize(crStream, myObject);
crStream.Close();
fileStream.Close();
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static T GeneralDeserialize<T>(string path)
{
T retObj;
using (var file = File.OpenRead(path))
{
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes(abcStr[6].ToString() + abcStr[0].ToString() + abcStr[17].ToString() + abcStr[10].ToString() + abcStr[20].ToString() + abcStr[8].ToString() + abcStr[4].ToString() + abcStr[12].ToString());
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(abcStr[16].ToString() + abcStr[10].ToString() + abcStr[7].ToString() + abcStr[1].ToString() + abcStr[2].ToString() + abcStr[18].ToString() + abcStr[14].ToString() + abcStr[21].ToString());
CryptoStream crStream = new CryptoStream(file, cryptic.CreateDecryptor(), CryptoStreamMode.Read);
retObj = Serializer.Deserialize<T>(crStream);
crStream.Close();
file.Close();
}
return retObj;
}
}