所謂的序列化,意思就只是將資料保存成二進位檔(連物件本身都可以保存),以後需要時再反序列化讀取內容

 

BinaryFormatter 是微軟在.Net 2.0才開始加入的功能

 


static void Main(string[] args)
        {
            Book book = new Book("Yang的部落格");
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = new FileStream("D:/test.dat", FileMode.Create))
            {
                bf.Serialize(fs, book);//寫入資料
                book = null;//清除book物件
            }
            using (FileStream fs = new FileStream("D:/test.dat", FileMode.Open))
            {
                book = (Book)bf.Deserialize(fs);//反序列化
            }

            Console.WriteLine(book.getBookName());
            Console.Read();//停止CMD畫面,以觀看結果
        }

        [Serializable]//允許Book被序列化
        class Book
        {
            private string bookName;

            public Book(string bookName)
            {
                this.bookName = bookName;
            }

            public string getBookName()
            {
                return bookName;
            }
        }


 

arrow
arrow
    全站熱搜

    Yang 發表在 痞客邦 留言(0) 人氣()