1、BinaryFormatter进行串行化
[Serializable]
public class ClassToSerialize
{
public int Id = 100;
public string Name = "Name";
[NonSerialized]
public string Sex = "男";
}
internal class SerializeOperation
{
public static void BfSerializeNow(object c)
{
using (var fileStream = new FileStream("temp.dat", FileMode.Create))
{
var b = new BinaryFormatter();
b.Serialize(fileStream, c);
}
}
public static object BfDeSerializeNow()
{
object c = null;
using (var filestream = new FileStream("temp.dat",FileMode.Open,FileAccess.Read,FileShare.Read))
{
var b = new BinaryFormatter();
c = b.Deserialize(filestream);
}
return c;
}
}
private static void Main(string[] args)
{
var c = new ClassToSerialize();
SerializeOperation.BfSerializeNow(c);
var c1 = SerializeOperation.BfDeSerializeNow() as ClassToSerialize;
if (c1 != null)
{
Console.WriteLine(c1.Id);
}
Console.ReadKey();
}