序列化与反序列化 BinaryFormatter.Serialize 方法 (Stream, Object)

 1 using System;
 2 using System.IO;
 3 using System.Collections;
 4 using System.Runtime.Serialization.Formatters.Binary;
 5 using System.Runtime.Serialization;
 6 
 7 public class App 
 8 {
 9     [STAThread]
10     static void Main() 
11     {
12         Serialize();
13         Deserialize();
14     }
15 
16     static void Serialize() 
17     {
18         // Create a hashtable of values that will eventually be serialized.
19         Hashtable addresses = new Hashtable();
20         addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
21         addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
22         addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");
23 
24         // To serialize the hashtable and its key/value pairs,  
25         // you must first open a stream for writing. 
26         // In this case, use a file stream.
27         FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
28 
29         // Construct a BinaryFormatter and use it to serialize the data to the stream.
30         BinaryFormatter formatter = new BinaryFormatter();
31         try 
32         {
33             formatter.Serialize(fs, addresses);
34         }
35         catch (SerializationException e) 
36         {
37             Console.WriteLine("Failed to serialize. Reason: " + e.Message);
38             throw;
39         }
40         finally 
41         {
42             fs.Close();
43         }
44     }
45 
46    
47     static void Deserialize() 
48     {
49         // Declare the hashtable reference.
50         Hashtable addresses  = null;
51 
52         // Open the file containing the data that you want to deserialize.
53         FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
54         try 
55         {
56             BinaryFormatter formatter = new BinaryFormatter();
57 
58             // Deserialize the hashtable from the file and 
59             // assign the reference to the local variable.
60             addresses = (Hashtable) formatter.Deserialize(fs);
61         }
62         catch (SerializationException e) 
63         {
64             Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
65             throw;
66         }
67         finally 
68         {
69             fs.Close();
70         }
71 
72         // To prove that the table deserialized correctly, 
73         // display the key/value pairs.
74         foreach (DictionaryEntry de in addresses) 
75         {
76             Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
77         }
78     }
79 }

 

posted on 2012-09-20 10:25  烟雨飘零  阅读(3468)  评论(0编辑  收藏  举报

导航