Recipe 5.14. Persisting a Collection Between Application SessionsProblemYou have a collection such as an ArrayList, List<T>, Hashtable, or Dictionary<T,U> in which you are storing application information. You can use this information to tailor the application's environment to the last known settings (e.g., window size, window placement, currently displayed toolbars). You can also use it to allow the user to start the application at the same point where it was last shut down. In other words, if the user is editing an invoice and needs to shut down the computer for the night, the application will know exactly which invoice to initially display when the application is started next time. SolutionSerialize the object(s) to and from a file: public static void SaveObj<T>(T obj, string dataFile) { FileStream FS = File.Create(dataFile); BinaryFormatter binSerializer = new BinaryFormatter( ); binSerializer.Serialize(FS, obj); FS.Close( ); } public static T RestoreObj<T>(string dataFile) { FileStream FS = File.OpenRead(dataFile); BinaryFormatter binSerializer = new BinaryFormatter( ); T obj = (T)binSerializer.Deserialize(FS); FS.Close( ); return (obj); } DiscussionThe dataFile parameter accepts a string value to use as a filename. The SaveObj<T> method accepts an object and attempts to serialize it to a file. Conversely, the RestoreObj<T> method removes the serialized object from the file created in the SaveObj<T> method. The TestSerialization utility shown in Example 5-5 demonstrates how to use these methods to serialize a Hashtable object and a List<int> object (note that this will work for any type that is marked with the SerializableAttribute). Example 5-5. Persisting a collection between application sessions
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 AlsoSee the "ArrayList Class," "Hashtable Class," "List<T> Class," "Dictionary<T,U> Class," "File Class," and "BinaryFormatter Class" topics in the MSDN documentation. |