Q: object serialization
Hello everybody.
I have a class. In this class I have a hashtable. I want whenever I fill this hashtable with information, the next time I start the program to be able to use the filled hashtable. I mean, if there is a way to skip filling it with every new initialization of the program. If there is a way to export the hashtable when it is filled and the next time to load it, I dunno.
Any ideas?
respect,
chire
Scott LyslePosted Nov 5, 2006, 10:09 PM
Here is one approach to doing what you want. Instead of a hashtable (which would also work) this uses a serializable class. I tend to put objects into a hashtable and deserialize the objects when pulling them back out of the hash using a similar approach but this example is pretty easy to follow and it seems like you could use it from the description you have provided.
Anyway, I hope it helps,
using
System;using
System.IO;using
System.Runtime.Serialization.Formatters.Binary;namespace
SerializableThis{
[
Serializable] class Person{
public string FirstName; public string LastName; public int Age; public string Street; public string City; public string State;}
class Class1{
[
STAThread] static void Main(string[] args){
Person pers = new Person();pers.FirstName =
"Cal";pers.LastName =
"Worthington";pers.Age = 96;
pers.Street =
"100 North Main";pers.City =
"Los Angeles";pers.State =
"CA"; Stream WriteStream = File.Create("C:\\Temp\\people.bin"); BinaryFormatter bf = new BinaryFormatter();bf.Serialize(WriteStream, pers);
WriteStream.Close();
Person pers2 = new Person(); Console.WriteLine("Before Serialization:\n"); Console.WriteLine("First Name: " + pers2.FirstName); Console.WriteLine("Last Name: " + pers2.LastName); Console.WriteLine("Age: " + pers2.Age); Console.WriteLine("Street: " + pers2.Street); Console.WriteLine("City: " + pers2.City); Console.WriteLine("State: " + pers2.State);
Stream ReadStream = File.OpenRead("C:\\Temp\\people.bin"); BinaryFormatter BinaryRead = new BinaryFormatter();pers2 = (
Person)BinaryRead.Deserialize(ReadStream);ReadStream.Close();
Console.WriteLine("\n\nAfter Deserialization:\n"); Console.WriteLine("First Name: " + pers2.FirstName); Console.WriteLine("Last Name: " + pers2.LastName); Console.WriteLine("Age: " + pers2.Age); Console.WriteLine("Street: " + pers2.Street); Console.WriteLine("City: " + pers2.City); Console.WriteLine("State: " + pers2.State); Console.ReadLine();}
}
}