二进制序列化

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace WebApplication1.Serialize
{
    public partial class Binary1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        //二进制序列化不同于 XMLSerializer 类,后者只序列化公共字段。
   
        protected void Button1_Click(object sender, EventArgs e)
        {
            MyObject obj = new MyObject();
            obj.n1 = 1;
            obj.n2 = 24;
            obj.str = "Some String";
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("C:/MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, obj);
            stream.Close();
        }
        [Serializable]
        public class MyObject
        {
            public int n1 = 0;
            public int n2 = 0;
            public String str = null;
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream("C:/MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
            MyObject obj = (MyObject)formatter.Deserialize(stream);
            stream.Close();

            // Here's the proof.

            Response.Write("n1: {0}"+ obj.n1+"<br/>");
            Response.Write("n2: {0}" + obj.n2 + "<br/>");
            Response.Write("str: {0}" + obj.str + "<br/>");
        }
        //上面所用的 BinaryFormatter 非常有效,生成了非常简洁的字节流。
        //通过该格式化程序序列化的所有对象也可以通过该格式化程序进行反序列化,这使该工具对于序列化将在 .NET Framework 上被反序列化的对象而言十分理想。
        //需要特别注意的是,在反序列化一个对象时不调用构造函数。出于性能方面的原因对反序列化施加了该约束。
        //但是,这违反了运行库与对象编写器之间的一些通常约定,开发人员应确保他们在将对象标记为可序列化时了解其后果。
        //如果可移植性是必需的,则转为使用 SoapFormatter。
        //只需用 SoapFormatter 代替上面代码中的 BinaryFormatter,
        //并且如前面一样调用 Serialize 和 Deserialize。此格式化程序为上面使用的示例生成以下输出。
    }

原文地址:https://www.cnblogs.com/yidianfeng/p/1372372.html