c#object对象与二进制转换方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 //引入三个命名空间
 7 using System.Runtime.Serialization;
 8 using System.Runtime.Serialization.Formatters.Binary;
 9 using System.IO;
10 
11 namespace Logistics
12 {
13     public class SerializeObjectToString
14     {
15         //将Object类型对象(注:必须是可序列化的对象)转换为二进制序列字符串
16         public string SerializeObject(object obj)
17         {
18             IFormatter formatter = new BinaryFormatter();
19             string result = string.Empty;
20             using (MemoryStream stream = new MemoryStream())
21             {
22                 formatter.Serialize(stream, obj);
23                 byte[] byt = new byte[stream.Length];
24                 byt = stream.ToArray();
25                 //result = Encoding.UTF8.GetString(byt, 0, byt.Length);
26                 result = Convert.ToBase64String(byt);
27                 stream.Flush();
28             }
29             return result;
30         }
31         //将二进制序列字符串转换为Object类型对象
32         public object DeserializeObject(string str)
33         {
34             IFormatter formatter = new BinaryFormatter();
35             //byte[] byt = Encoding.UTF8.GetBytes(str);
36             byte[] byt = Convert.FromBase64String(str);
37             object obj = null;
38             using (Stream stream = new MemoryStream(byt, 0, byt.Length))
39             {
40                 obj = formatter.Deserialize(stream);
41             }
42             return obj;
43         }
44     }
45 }

猜你喜欢

转载自www.cnblogs.com/leizhui/p/11750415.html
今日推荐