背景:最近在开发的时候,其它同事会在本地存储一个二进制文件,而我需要将二进制文件读取出来,然后将读取出来的实体对象邦定到界面上。

    实体:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. namespace _06_实体和_二进制_相互转换.Model
    7. {
    8. /// <summary>
    9. /// 需要存储的二进制实体
    10. /// </summary>
    11. [Serializable]
    12. public class Student
    13. {
    14. public string StudentNo { get; set; }
    15. public string StudentName { get; set; }
    16. public int StudentSex { get; set; }
    17. public string StudentAddress { get; set; }
    18. }
    19. }

    备注:实体需要标注为可序列化

    读写bin文件,bin文件中存储二进制

    1. using _06_实体和_二进制_相互转换.Model;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.IO;
    5. using System.Linq;
    6. using System.Runtime.Serialization.Formatters.Binary;
    7. using System.Text;
    8. using System.Threading.Tasks;
    9. namespace _06_实体和_二进制_相互转换
    10. {
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Student student = ReadStudent(); //首先返回一个空的Student对象
    16. student.StudentNo = "001";
    17. student.StudentName = "Rotu";
    18. student.StudentSex = 1;
    19. student.StudentAddress = "HB";
    20. SerializeToBinFile(student); //序列化到bin文件
    21. Student newStudent = ReadStudent(); //重新读取
    22. Console.WriteLine(newStudent.StudentNo);
    23. Console.ReadKey();
    24. }
    25. /// <summary>
    26. /// 读取二进制文件 返回实体
    27. /// </summary>
    28. /// <returns></returns>
    29. public static Student ReadStudent()
    30. {
    31. BinaryFormatter formatter = new BinaryFormatter();
    32. Student student = null;
    33. string url = @"D:\Rotu\Project.Rotu.Test\06 实体和 二进制 相互转换\File\student.bin";
    34. using (FileStream fs = File.OpenRead(url))
    35. {
    36. try
    37. {
    38. student = (Student)formatter.Deserialize(fs);
    39. }
    40. catch (Exception)
    41. {
    42. student = new Student();
    43. }
    44. }
    45. return student;
    46. }
    47. public static void SerializeToBinFile(Student student)
    48. {
    49. string url = @"D:\Rotu\Project.Rotu.Test\06 实体和 二进制 相互转换\File\student.bin";
    50. BinaryFormatter formatter = new BinaryFormatter();
    51. FileStream fs = new FileStream(url,FileMode.Open,FileAccess.ReadWrite);
    52. formatter.Serialize(fs,student);
    53. fs.Close();
    54. }
    55. }
    56. }

    备注:读写二进制使用BinaryFormatter这个类,用来序列化和反序列化二进制文件