下面小编就为大家带来一篇protobuf对象二进制序列化存储(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
首先下载protobuf库,可以用Nuget。
demo:
using System;
namespace Tools
{
public class BufHelp
{
/// <summary>
/// 对象锁
/// </summary>
private readonly static Object Locker = new Object();
///// <summary>
///// 读写分离锁
///// </summary>
///// <remarks>aaaaa</remarks>
//private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
/// <summary>
/// 序列化-表字段业务信息
/// </summary>
public static bool ProtoBufSerialize<T>(T model, string filename) where T : class
{
try
{
string binpath = Config.KeyCenter.KeyBaseDirectory + @"Config\";
if (!System.IO.Directory.Exists(binpath))
System.IO.Directory.CreateDirectory(binpath);
lock (Locker)
{
using (var file = System.IO.File.Create(binpath + filename))
{
ProtoBuf.Serializer.Serialize<T>(file, model);
return true;
}
}
}
catch
{
return false;
}
}
public static T ProtoBufDeserialize<T>(string filename) where T : class
{
var dbpath = Config.KeyCenter.KeyBaseDirectory + @"Config\" + filename;
if (System.IO.File.Exists(dbpath))
{
lock (Locker)
{
using (var file = System.IO.File.OpenRead(dbpath))
{
var result = ProtoBuf.Serializer.Deserialize<T>(file);
return result;
}
}
}
return default(T);
}
}
}/// <summary>
/// 序列化
/// </summary>
public static string Serialize<T>(T t) where T : class
{
using (MemoryStream ms = new MemoryStream())
{
ProtoBuf.Serializer.Serialize<T>(ms, t);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// 反序列化
/// </summary>
public static T DeSerialize<T>(string content) where T : class
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
T t = ProtoBuf.Serializer.Deserialize<T>(ms);
return t;
}
}
以上这篇protobuf对象二进制序列化存储(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:protobuf对象二进制序列化存储(详解)


基础教程推荐
猜你喜欢
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C# 解析XML和反序列化的示例 2023-04-14
- Unity shader实现高斯模糊效果 2023-01-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#中的Linq to JSON操作详解 2023-06-08