O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required