using (MemoryStream ms = new MemoryStream()){ BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms,p); // 获取内存流中的字节数组 byte[] data = ms.GetBuffer(); // 将字节数组写入文件 File.WriteAllBytes(Application.dataPath + "/person.dat", data); // 关闭内存流 (using 语句会自动调用) ms.Close(); }
方法二:使用文件流进行存储,主要用于存储到文件中
文件流对象:类名为FileStream
1 2 3 4 5 6
using(FileStream fs = new FileStream(Application.dataPath + "/person.dat",FileMode.OpenOrCreate,FileAccess.Write )){ BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs,p); fs.Flush(); fs.Close(); }
反序列化
1.反序列文件中的数据,使用文件流进行反序列化。
首先打开文件,使用2进制格式化类。
1 2 3 4 5 6
using (FileStream fs = FileStream.Open(Application.dataPath + "/person.dat",FileMode.Open,FileAccess.Read)){ BinaryFormatter bf = new BinaryFormatter(); //bf.Deserialize(fs)是一个Object对象 ,所以需要进行数据转换 Person p = bf.Deserialize(fs) as Person; fs.Close(); }
2.反序列化网络传输过来的2进制数据
使用内存流类:类名为MemoryStream,命名空间System.IO
1 2 3 4 5
using (MemoryStream ms = new MemoryStream(bytes)){ BinaryFormatter bf = new BinaryFormatter(); Person p = bf.Deserialize(ms) as Person; bf.Close(); }
Person p = new Person(); publicbyte Key = 11; using (MemoryStream ms = new MemoryStream()){ BinaryFormatter bf = new BinaryFormatter(); bf.serialize(ms,p); byte[] bytes = ms.GetBuffer(); //异或加密 for(int i = 0;i<bytes.Length;i++){ bytes[i]^=Key; } File.WriteAllBytes(Application.dataPath + "/Person.dat",bytes); ms.Close(); } byte[] bytes2 = File.ReadAllBytes(Application.dataPath + "/Person.dat"); for(int i = 0;i<bytes2.Length;i++){ bytes2[]^ =Key; } using (MemoryStream ms = new MemoryStream(bytes)){ BinaryFormatter bf = new BinaryFormatter(); Person p = bf.Deserialize(ms) as Person; bf.Close(); }