示例#1
0
        public static void Write_v2(string path)
        {
            Console.WriteLine("Creating a version 2 object");

            Person_v2 p2 = new Person_v2();

            p2.Name = "Elizabeth";
            p2.ID   = 2006;

            Console.WriteLine("Object data includes an ID");
            Console.WriteLine("\t Name: {0}", p2.Name);
            Console.WriteLine("\t ID: {0} \n", p2.ID);
            // Create an instance of the DataContractSerializer.
            //依靠DataContractSerializer來做序列化寫入(先告訴此物件要序列化的物件類別)
            DataContractSerializer serializer = new DataContractSerializer(typeof(Person_v2));

            Console.WriteLine("Serializing the v2 object to a file. \n\n");
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
            serializer.WriteObject(fs, p2);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();//用MemoryStream來看看真實數據
            serializer.WriteObject(ms, p2);
            byte[] data = ms.ToArray();
            Console.WriteLine("物件轉成XML數據的內容:\n{0}", Encoding.ASCII.GetString(data));
            ms.Close();
            fs.Close();
        }
示例#2
0
        public static void Read_v2(string path)
        {
            //從資料流取得檔案
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
            //並使用DataContractSerializer還原回物件
            DataContractSerializer serializer = new DataContractSerializer(typeof(Person_v2));

            Console.WriteLine("Deserializing new data to version 2 \n\n");

            Person_v2 p2 = serializer.ReadObject(fs) as Person_v2;

            fs.Close();

            Console.WriteLine("The data includes the old ID field value. \n");
            Console.WriteLine("\t (New) Name: {0}", p2.Name);
            Console.WriteLine("\t ID: {0} \n", p2.ID);
        }