C# 类序列化为文件,文件反序列化为类(二进制)

(1)添加引用

 (2)在将要序列化的类中引用 using ProtoBuf; 并且在类之前添加字段 [Serializable] 变量之前添加字段 ProtoMember 效果如下所示:

 1 using System;
 2 using ProtoBuf;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace eaa
 9 {
10     [Serializable]  // 提示该类可序列化
11     [ProtoContract]
12     public class Company
13     {
14         [ProtoMember(1)]
15         public string Name;
16         [ProtoMember(2)]
17         public string isComplete;
18         [ProtoMember(3)]
19         public List<Comment> comment = new List<Comment>();
20     }
21     [Serializable]  // 提示该类可序列化
22     [ProtoContract]
23     public class Comment
24     {
25         [ProtoMember(1)]
26         public string time;
27         [ProtoMember(2)]
28         public string comment;
29         [ProtoMember(3)]
30         public string verifier;
31         [ProtoMember(4)]
32         public string complete;
33     }
34 }

(3)建立方法用于将类序列化并保存为二进制文件

 1         /// <summary>
 2         /// 将类序列化并保存成文件
 3         /// </summary>
 4         /// <param name="filePath"></param>
 5         /// <param name="outputData"></param>
 6         /// <returns></returns>
 7         public static bool SerializetoFile(string filePath, Dictionary<string, Company> outputData)
 8         {
 9             try
10             {
11                 FileStream fs = new FileStream(filePath, FileMode.Create);
12                 BinaryFormatter bf = new BinaryFormatter();
13                 bf.Serialize(fs, outputData);
14                 fs.Close();
15                 return true;
16             }
17             catch (Exception ex)
18             {
19                 Console.WriteLine(ex.Message);  // 打印错误日志
20                 return false;
21             }
22         }

(4)建立方法用于将二进制文件反序列化为对应的类

 1         /// <summary>
 2         /// 将文件反序列化为类
 3         /// </summary>
 4         /// <param name="filePath"></param>
 5         /// <returns></returns>
 6         public static bool FiletoSerialize(ref Dictionary<string, Company> inputData,string filePath)
 7         {
 8             try
 9             {
10                 FileStream fs = new FileStream(filePath, FileMode.Open);
11                 BinaryFormatter bf = new BinaryFormatter();
12                 inputData = bf.Deserialize(fs) as Dictionary<string, Company>;
13                 fs.Close();
14                 return true;
15             }
16             catch (Exception ex)
17             {
18                 Console.WriteLine(ex.Message);  // 打印错误日志
19                 return false;
20             }
21         }

猜你喜欢

转载自www.cnblogs.com/lijinying/p/12681048.html
今日推荐