
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Persisting a Collection Between Application Sessions
|
315
See Also
See the “ICollection Interface” and “Array Class” topics in the MSDN documentation.
5.14 Persisting a Collection Between Application
Sessions
Problem
You have a collection such as an ArrayList, List<T>, Hashtable,orDictionary<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.
Solution
Serialize 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);
}
Discussion ...