(2010-08-11) C#.NET 序列化

摘要:(2010-08-11) C#.NET 序列化

自訂序列化類別

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace winmdo06
{
    //特徵描述Attribute Class
    [System.SerializableAttribute()]
    public class Employee
    {
        //Data Field
        private String _id;

        [System.Xml.Serialization.XmlAttribute()]public String Id
        {
            get { return _id; }
            set { _id = value; }
        }
        private String _name;

        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private Decimal _salary;

        public Decimal Salary
        {
            get { return _salary; }
            set { _salary = value; }
        }
        private DateTime _birthDate;

        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public DateTime BirthDate
        {
            get { return _birthDate; }
            set { _birthDate = value; }
        }
    }
}

主要程式碼

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace winmdo06
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //建構物件 
            Employee emp = new Employee() { Id = "0001", Name = "eric", BirthDate = new DateTime(2000, 1, 1), Salary = 50000 };
            //寫出去???? 寫成XML 
            //1建立串流
            System.IO.Stream fs = new System.IO.FileStream(@"c:\emp.bin", System.IO.FileMode.Create, System.IO.FileAccess.Write);
            ////2.建立寫出器
            //System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(fs, System.Text.Encoding.UTF8);
            ////縮排
            //writer.Formatting = System.Xml.Formatting.Indented;
            ////設備
            //System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Employee));

            //ser.Serialize(writer, emp);
            //writer.Flush();
            //fs.Close();

            //Binary 已有型別 常做如..授權等....使用者不易變更
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ser = 
                new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            ser.Serialize(fs, emp);
            fs.Close();



        }

        private void button2_Click(object sender, EventArgs e)
        {
            //1建立串流
            System.IO.Stream fs = new System.IO.FileStream(@"c:\emp.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read);
            //2.準備設定
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Employee));
            Employee emp = (Employee)ser.Deserialize(fs);
            MessageBox.Show(emp.Name);
        }
    }
}

補充 2010-08-11.rar