Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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 ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata