Recipe 9.16 Persisting a Collection Between Application Sessions

Recipe 9.16 Persisting a Collection Between Application Sessions

Problem

You have a collection such as an ArrayList or a Hashtable in which you are storing application information. This information can be used to tailor the application's environment to the last known settings (e.g., window size, window placement, currently displayed toolbars ), or the information can be used to allow the user to start using the application at the same point where the application was last shut down. In other words, if the user were editing an invoice and needed to shut down the computer for the night, the application would know exactly which invoice to initially display when the application was started next time.

Solution

Serialize the object(s) to and from a file:

 public static void SaveObj(object obj) {     FileStream FS = File.Create(dataFile);     BinaryFormatter binSerializer = new BinaryFormatter( );     binSerializer.Serialize(FS, obj);     FS.Close( ); } public static object RestoreObj( ) {     FileStream FS = File.OpenRead(dataFile);     BinaryFormatter binSerializer = new BinaryFormatter( );     object obj = binSerializer.Deserialize(FS);     FS.Close( );     return (obj); } 

Discussion

The DataFile constant defines a string value to use as a filename. The SaveObj method accepts an object and attempts to serialize it to a file. Conversely, the RestoreObj method removes the serialized object from the file created in the SaveObj method.

The following code shows how to use these methods to serialize a Hashtable object (note that this will work for any type that is marked with the SerializableAttribute ):

 public static void TestSerialization( ) {     // Create an object to save/restore to/from a file     Hashtable HT = new Hashtable( );     HT.Add(0, "Zero");     HT.Add(1, "One");     HT.Add(2, "Two");     // Display this object's contents and save it to a file     foreach (DictionaryEntry DE in HT)         Console.WriteLine(DE.Key + " : " + DE.Value);     SaveObj(HT);     // Restore this object from the same file and display its contents     Hashtable HTNew = new Hashtable( );     HTNew = (Hashtable)RestoreObj( );     foreach (DictionaryEntry DE in HTNew)         Console.WriteLine(DE.Key + " : " + DE.Value); } 

If you serialize your objects to disk at specific points in your application, you can then deserialize them and return to a known state; for instance, in the event of an unintended shutdown.

See Also

See the "ArrayList Class," "Hashtable Class," "File Class," and "BinaryFormatter Class" topics in the MSDN documentation.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net