首页 > 其他 > 详细

Protobuf对象写入文件与从文件读取的工具

时间:2020-07-02 19:31:42      阅读:242      评论:0      收藏:0      [点我收藏+]

前提需要安装Protobuf。

工具代码:

 1 using System;
 2 using System.IO;
 3 
 4 public class ProtobufTool
 5 {
 6     #region Protobuff序列化
 7 
 8     public static int SerializeProtobuf(object obj, string filePath)
 9     {
10         using (MemoryStream ms = new MemoryStream())
11         {
12             ms.Seek(0, SeekOrigin.Begin);
13             ms.SetLength(0);
14             //TODO需要安装ProtoBuf
15             //ProtoBuf.Serializer.Serialize(ms, obj);
16             ms.Seek(0, SeekOrigin.Begin);
17             int totalDataLen = (int)ms.Length;
18             if (totalDataLen > 0)
19             {
20                 using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
21                 {
22                     fileStream.Write(ms.GetBuffer(), 0, totalDataLen);
23                 }
24             }
25         }
26         return 0;
27     }
28 
29     public static object DeSerializeProtobuf(string filePath, Type type)
30     {
31         using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read))
32         {
33             if (null != fileStream)
34             {
35                 fileStream.Seek(0, SeekOrigin.Begin);
36                 using (MemoryStream ms = new MemoryStream())
37                 {
38                     ms.SetLength(fileStream.Length);
39                     fileStream.Read(ms.GetBuffer(), 0, (int)fileStream.Length);
40                     //TODO需要安装ProtoBuf
41                     object obj = null;// ProtoBuf.Serializer.DeSerialize(type, ms);
42                     ms.Flush();
43                     return obj;
44                 }
45             }
46         }
47         return null;
48     }
49 
50     #endregion
51 }

 

Protobuf对象写入文件与从文件读取的工具

原文:https://www.cnblogs.com/luguoshuai/p/13226545.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!