2014年2月10日 星期一

[C#/Serialize] 在不同檔案間傳遞結構(structure)利用Serialize和Deserialize

首先必須先創建一個"類別庫"(新增->類別庫 in VS2012)

一定要有關鍵字[Serializable]否則無法,然後建立一個Struct

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;

namespace PassingStruct
{
    public class Class1
    {
    }

    [Serializable]
    public struct MemberList
    {
        private BindingList<Member> _MemberCollection;
        public BindingList<Member> MemberCollection
        {
            get
            {
                if (this._MemberCollection == null)
                    this._MemberCollection = new BindingList<Member>();
                return this._MemberCollection;
            }
        }
    }

    [Serializable]
    public struct Member
    {
        public int ID { get; set; }
        public int age { get; set; }
        public string name { get; set; }
        public int number { get; set; }
        public string sex { get; set; }
    }
}

編譯時會產生錯誤訊息,但其實還是成功(在Debug資料夾內)會有一個dll檔產生。

OK,到這邊,需要將dll檔加入參考到要序列化的程式碼。

以下為序列化程式碼

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;


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

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

        private void button1_Click(object sender, EventArgs e)
        {

            PassingStruct.MemberList list = CreateClass();
            SerializeToBinary("list.dat", list);
        }
        public PassingStruct.MemberList CreateClass()
        {
            PassingStruct.MemberList list = new PassingStruct.MemberList();
            list.MemberCollection.Add(new PassingStruct.Member() { ID = 1, age = 18, name = "paul walker", number = 999, sex = "male" });
            list.MemberCollection.Add(new PassingStruct.Member() { ID = 2, age = 20, name = "jonathan brewster", number = 123, sex = "female" });
            return list;
        }
        public static void SerializeToBinary(string FileName, object Object)
        {
            Stream stream = null;
            IFormatter/*用於格式化已經序列化的東西*/ format = new BinaryFormatter();//以二進位格式序列化和還原序列化物件
            try
            {
                stream = new FileStream(FileName,FileMode.Create,FileAccess.Write,FileShare.Read);
                format.Serialize(stream, Object);
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PassingStruct.MemberList list = DeserializeFromBinary<PassingStruct.MemberList>("list.dat");
        }

        public static T DeserializeFromBinary<T>(string FileName)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = null;
            try
            {
                stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                object obj = formatter.Deserialize(stream);
                if (obj == null)
                    return default(T);
                else
                    return (T)obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
    }
}

注意到在using這邊
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using PassingStruct;//這個就是dll檔,除了在Visual Studio專案裡面選擇 專案->加入參考->瀏覽->dll檔,還要加入這一行

然後,序列化基本上就完成了。接著就是反序列化:(以下為反序列化程式碼)

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;

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

namespace serialize_transfer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //File.wr
        }

        public static T DeserializeFromBinary<T>(string FilePath)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = null;
            try
            {
                stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                object obj = formatter.Deserialize(stream);//問題出在這邊
                if (obj == null)
                    return default(T);
                else
                    return (T)obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PassingStruct.MemberList list = DeserializeFromBinary<PassingStruct.MemberList>(@"C:\Users\daniel\Dropbox\Visual Studio 2012\Projects\Binary_filestreame\Binary_filestreame\bin\Debug\list.dat");
        }
    }
}

同樣也需要加入參考以及+using的程式碼 記得反序列化路徑要弄對就好了。

應用的部分,可使用在DataGridView上面

BindingSource Source = new BindingSource();
public void Form1_Load(object sender, EventArgs e)
{
    this.Source.DataSource = CreateClass().MemberCollection;

    this.dataGridView1.DataSource = this.Source;
    this.bindingNavigator1.BindingSource = this.Source;
    this.textBox1.DataBindings.Add("Text", this.Source, "ID");
    this.textBox2.DataBindings.Add("Text", this.Source, "name");
    this.textBox3.DataBindings.Add("Text", this.Source, "age");
    this.textBox4.DataBindings.Add("Text", this.Source, "phone");
    this.textBox5.DataBindings.Add("Text", this.Source, "sex");
}

End

參考資料: 余小章.net教學


沒有留言:

張貼留言