[C#]网络字节流处理
在网络上传数据时,可以先把对象的数据序列化成字节数组,在客户端接收到数据后,再反序列化成对象,在转换成自己的类型
我写了两个方法,可以直接使用,非常方便:
一、对象序列化为字节数组
我写了两个方法,可以直接使用,非常方便:
一、对象序列化为字节数组
1 /// <summary>
2 /// 二进制方式将object对象序列化到字节数组中
3 /// </summary>
4 /// <param name= "obj "> </param>
5 /// <returns> </returns>
6 public static byte[] SerializeByBinary(Object obj)
7 {
8 byte[] buffer2;
9 try
10 {
11 var memoryStream = new MemoryStream();
12 var formatter1 = new BinaryFormatter();
13 formatter1.Serialize(memoryStream, obj);
14 byte[] buffer1 = memoryStream.ToArray();
15 memoryStream.Close();
16 buffer2 = buffer1;
17 }
18 catch
19 {
20 buffer2 = null;
21 }
22 return buffer2;
23
24 }
2 /// 二进制方式将object对象序列化到字节数组中
3 /// </summary>
4 /// <param name= "obj "> </param>
5 /// <returns> </returns>
6 public static byte[] SerializeByBinary(Object obj)
7 {
8 byte[] buffer2;
9 try
10 {
11 var memoryStream = new MemoryStream();
12 var formatter1 = new BinaryFormatter();
13 formatter1.Serialize(memoryStream, obj);
14 byte[] buffer1 = memoryStream.ToArray();
15 memoryStream.Close();
16 buffer2 = buffer1;
17 }
18 catch
19 {
20 buffer2 = null;
21 }
22 return buffer2;
23
24 }
二、字节数组反序列化为对象
1 /// <summary>
2 /// 二进制方式字节数组中数据还原为对象
3 /// </summary>
4 /// <param name= "obj "> </param>
5 /// <returns> </returns>
6 public static object DeSerializeByBinary(byte[] byt)
7 {
8 object obj2;
9 try
10 {
11 var memoryStream = new MemoryStream(byt);
12 var formatter = new BinaryFormatter();
13 object obj1 = formatter.Deserialize(memoryStream);
14 memoryStream.Close();
15 obj2 = obj1;
16 }
17 catch
18 {
19 obj2 = null;
20 }
21 return obj2;
22 }
2 /// 二进制方式字节数组中数据还原为对象
3 /// </summary>
4 /// <param name= "obj "> </param>
5 /// <returns> </returns>
6 public static object DeSerializeByBinary(byte[] byt)
7 {
8 object obj2;
9 try
10 {
11 var memoryStream = new MemoryStream(byt);
12 var formatter = new BinaryFormatter();
13 object obj1 = formatter.Deserialize(memoryStream);
14 memoryStream.Close();
15 obj2 = obj1;
16 }
17 catch
18 {
19 obj2 = null;
20 }
21 return obj2;
22 }
将object转换成自己的对象类型就可以了