微软文档中有写如何使用文件流FileStream对类进行序列化Serialize和反序列化Deserialize。
参考:基本序列化
[Serializable]
public class MyObject {
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
序列化过程:
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
反序列化过程:
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(stream);
stream.Close();
// Here's the proof.
Console.WriteLine("n1: {0}", obj.n1);
Console.WriteLine("n2: {0}", obj.n2);
Console.WriteLine("str: {0}", obj.str);
如果使用内存流,代码如下:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Codeplex.Data;
namespace json
{
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
class Program
{
static void Main(string[] args)
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
//Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
Stream stream = new MemoryStream();
formatter.Serialize(stream, obj);
//stream.Close();
//Stream stream2 = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
stream.Seek(0, SeekOrigin.Begin);
MyObject obj2 = (MyObject)formatter.Deserialize(stream);
stream.Close();
// Here's the proof.
Console.WriteLine("n1: {0}", obj2.n1);
Console.WriteLine("n2: {0}", obj2.n2);
Console.WriteLine("str: {0}", obj2.str);
}
}
}
注意数据流的seek需要重新定位到起始地址:
stream.Seek(0, SeekOrigin.Begin);
否则会出现异常:
System.Runtime.Serialization.SerializationException:“End of Stream encountered before parsing was completed.”