1. using System;
    2. using System.Collections.Generic;
    3. using System.IO;
    4. using System.Linq;
    5. using System.Runtime.Serialization.Formatters.Binary;
    6. using System.Text;
    7. using System.Threading.Tasks;
    8. namespace _06序列化
    9. {
    10. class Program
    11. {
    12. static void Main(string[] args)
    13. {
    14. //要将序列化对象的类 标记为可以被序列化的
    15. //Person p = new Person();
    16. //p.Name = "张三";
    17. //p.Age = 10;
    18. //p.Gender = '男';
    19. //using (FileStream fsWrite = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Write))
    20. //{
    21. // BinaryFormatter bf = new BinaryFormatter();
    22. // bf.Serialize(fsWrite, p);
    23. //}
    24. //Console.WriteLine("序列化成功");
    25. //Console.ReadKey();
    26. Person p;
    27. using (FileStream fsRead = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Read))
    28. {
    29. BinaryFormatter bf = new BinaryFormatter();
    30. p = (Person)bf.Deserialize(fsRead);
    31. }
    32. Console.WriteLine(p.Name);
    33. Console.WriteLine(p.Age);
    34. Console.WriteLine(p.Gender);
    35. Console.ReadKey();
    36. }
    37. }
    38. [Serializable]
    39. public class Person
    40. {
    41. public string Name
    42. {
    43. get;
    44. set;
    45. }
    46. public int Age
    47. {
    48. get;
    49. set;
    50. }
    51. public char Gender
    52. {
    53. get;
    54. set;
    55. }
    56. }
    57. }