C# 物件序列化(serialization)讀/寫檔案 [二進位/二進制檔案]

C# 物件序列化(serialization)讀/寫檔案 [二進位/二進制檔案]

C# 物件序列化(serialization)讀/寫檔案 [二進位/二進制檔案]





Step0:資料建立

[Serializable]// *這一行很重要
class AnotherObj {}
class SomeObj {
public int x;// 該變數會被保存
public AnotherObj another; // 該物件也會被保存,但其類別需加上 [Serializable] 屬性(attribute)
}



Step1:引入 namespace

在 .cs 檔前頭加上 using System.Runtime.Serialization.Formatters.Binary;



Step2:建立序列化的串流

BinaryFormatter formatter = new BinaryFormatter();



Step3:開始序列化(serialize)

Stream output = File.Create(file_name);
formatter.Serialize(output, objectToSerialize);
output.Close();



Step4:反序列化(deserialize)

Stream input = File.OpenRead(file_name);
SomeObj obj = (SomeObj)formatter.Deserialize(input);

input.Close();


完整範例:

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

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

namespace CS_Object_serialization
{
    [Serializable] //表示該類可被序列化
    public class AppPar_serialization
    {
        public ArrayList ALPar;
        public AppPar_serialization()
        {
            ALPar = new ArrayList();
        }
    }

    class Program
    {
        static void Pause()
        {
            Console.Write("Press any key to continue...");
            Console.ReadKey(true);
        }
        static void Main(string[] args)
        {
            AppPar_serialization AppPAr01 = new AppPar_serialization();
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);
            AppPAr01.ALPar.Add(false);
            AppPAr01.ALPar.Add(true);

            //開始序列化(serialize)
            BinaryFormatter formatter01 = new BinaryFormatter();
            Stream output = File.Create("AppPar.par");
            formatter01.Serialize(output, AppPAr01);
            output.Close();

            //反序列化(deserialize)
            BinaryFormatter formatter02 = new BinaryFormatter();
            Stream input = File.OpenRead("AppPar.par");
            AppPar_serialization AppPAr012= (AppPar_serialization)formatter02.Deserialize(input);
            input.Close();

            for(int i=0;i< AppPAr012.ALPar.Count;i++)
            {
                Console.WriteLine("{0}\t{1}",i, (bool)(AppPAr012.ALPar[i]));
            }

            Pause();
        }
    }
} 



發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *