将数据结构类型序列化和反序列化(BinaryFormatter类)

简单例子如下:
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

加上命名空间

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //the struct to serializer
        [Serializable]
        public struct mydata
        {
            public string myname;
            public string mybirthday;
            public int age;
            public byte[] imageByte;
        }
//选择保存路径
        private void button1_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "XML文件|*.xml";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                textBox1.Text=saveFileDialog1.FileName;
        }
//将数据结构序列化到bat或其他格式文件中
        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
                return;
            mydata newdata = new mydata();
            newdata.myname = "龙域";
            newdata.mybirthday = "09-31";
            newdata.age = 23;
            newdata.imageByte = Encoding.Default.GetBytes("999adfklasdjfl".ToCharArray());
            IFormatter formatter = new BinaryFormatter();
            FileStream fs = new FileStream(textBox1.Text, FileMode.OpenOrCreate);
            formatter.Serialize(fs, newdata);
            fs.Close();
        }
//反序列化二进制文件
        private void button3_Click(object sender, EventArgs e)
        {
            IFormatter formter = new BinaryFormatter();
            FileStream fs = new FileStream(textBox1.Text,FileMode.Open);
            mydata mm=(mydata)formter.Deserialize(fs);
            MessageBox.Show("mm.Name="+mm.myname+"\r\n"+
                             "mm.bothday=" + mm.mybirthday + "\r\n" +
                             "mm.age="+mm.age+"\r\n"+
                             "mm.imageByte="+Encoding.Default.GetString(mm.imageByte));
            fs.Close();
        }
    }

你可能感兴趣的:(format)