GooglePrettify

2017年2月5日 星期日

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();

from : http://jashliao.pixnet.net/blog/post/206148241-c%23-%E7%89%A9%E4%BB%B6%E5%BA%8F%E5%88%97%E5%8C%96%EF%BC%88serialization%EF%BC%89%E8%AE%80-%E5%AF%AB%E6%AA%94%E6%A1%88

1 則留言:

  1. 我搬家了,今天剛好更新這一篇文章
    特的來留言分享
    http://jashliao.eu/wordpress/2015/11/13/c-%e7%89%a9%e4%bb%b6%e5%ba%8f%e5%88%97%e5%8c%96%ef%bc%88serialization%ef%bc%89%e8%ae%80%e5%af%ab%e6%aa%94%e6%a1%88/

    回覆刪除