5.11. Persisting a Collection Between Application Sessions
Problem
You 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, and 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.
Solution
Serialize the object(s) to and from a file:
public static void SaveObj<T>(T obj, string dataFile)
{
using (FileStream FS = File.Create(dataFile))
{
BinaryFormatter binSerializer = new BinaryFormatter( );
binSerializer.Serialize(FS, obj);
} }
public static T RestoreObj<T>(string dataFile)
{
T obj = default(T);
using (FileStream FS = File.OpenRead(dataFile))
{
BinaryFormatter binSerializer = new BinaryFormatter( );
obj = (T)binSerializer.Deserialize(FS);
}
return (obj); }Discussion
The 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 Recipe 5.11 demonstrates ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access