1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 using System.Runtime.Serialization.Formatters.Binary; 8 namespace test 9 { 10 class Program 1
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 using System.Runtime.Serialization.Formatters.Binary; 8 namespace test 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 //要将p这个对象 传输给对方电脑 15 //Person p = new Person(); 16 //p.Name = "张三"; 17 //p.Age = 19; 18 //p.Gender = ‘男‘; 19 //using (FileStream fsWrite = new FileStream(@"C:\Users\SpringRain\Desktop\111.txt", FileMode.OpenOrCreate, FileAccess.Write)) 20 //{ 21 // //开始序列化对象 22 // BinaryFormatter bf = new BinaryFormatter(); 23 // bf.Serialize(fsWrite, p); 24 //} 25 //Console.WriteLine("序列化成功"); 26 //Console.ReadKey(); 27 28 //接收对方发送过来的二进制 反序列化成对象 29 Person p; 30 using (FileStream fsRead = new FileStream(@"C:\Users\SpringRain\Desktop\111.txt", FileMode.OpenOrCreate, FileAccess.Read)) 31 { 32 BinaryFormatter bf = new BinaryFormatter(); 33 p = (Person)bf.Deserialize(fsRead); 34 } 35 Console.WriteLine(p.Name); 36 Console.WriteLine(p.Age); 37 Console.WriteLine(p.Gender); 38 Console.ReadKey(); 39 } 40 } 41 42 43 [Serializable] 44 public class Person 45 { 46 private string _name; 47 48 public string Name 49 { 50 get { return _name; } 51 set { _name = value; } 52 } 53 54 55 private char _gender; 56 57 public char Gender 58 { 59 get { return _gender; } 60 set { _gender = value; } 61 } 62 63 private int _age; 64 65 public int Age 66 { 67 get { return _age; } 68 set { _age = value; } 69 } 70 } 71 }