背景:最近在开发的时候,其它同事会在本地存储一个二进制文件,而我需要将二进制文件读取出来,然后将读取出来的实体对象邦定到界面上。
实体:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _06_实体和_二进制_相互转换.Model{/// <summary>/// 需要存储的二进制实体/// </summary>[Serializable]public class Student{public string StudentNo { get; set; }public string StudentName { get; set; }public int StudentSex { get; set; }public string StudentAddress { get; set; }}}
备注:实体需要标注为可序列化
读写bin文件,bin文件中存储二进制
using _06_实体和_二进制_相互转换.Model;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.Serialization.Formatters.Binary;using System.Text;using System.Threading.Tasks;namespace _06_实体和_二进制_相互转换{class Program{static void Main(string[] args){Student student = ReadStudent(); //首先返回一个空的Student对象student.StudentNo = "001";student.StudentName = "Rotu";student.StudentSex = 1;student.StudentAddress = "HB";SerializeToBinFile(student); //序列化到bin文件Student newStudent = ReadStudent(); //重新读取Console.WriteLine(newStudent.StudentNo);Console.ReadKey();}/// <summary>/// 读取二进制文件 返回实体/// </summary>/// <returns></returns>public static Student ReadStudent(){BinaryFormatter formatter = new BinaryFormatter();Student student = null;string url = @"D:\Rotu\Project.Rotu.Test\06 实体和 二进制 相互转换\File\student.bin";using (FileStream fs = File.OpenRead(url)){try{student = (Student)formatter.Deserialize(fs);}catch (Exception){student = new Student();}}return student;}public static void SerializeToBinFile(Student student){string url = @"D:\Rotu\Project.Rotu.Test\06 实体和 二进制 相互转换\File\student.bin";BinaryFormatter formatter = new BinaryFormatter();FileStream fs = new FileStream(url,FileMode.Open,FileAccess.ReadWrite);formatter.Serialize(fs,student);fs.Close();}}}
备注:读写二进制使用BinaryFormatter这个类,用来序列化和反序列化二进制文件
