[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     }

 二、字節數組反序列化為對象

 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     }

 將object轉換成自己的對象類型就可以了

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM