Hello group! :)
I want to create a config/status object, that will contain a Hashtable. This
object I would like to save through Serialization, but im having some
trouble. My hashtable contain some objects, from a class I created myself.
I read that I need to make my own "add" method, which I hopefully did
correct. I hope someone can spot my wrongdoings, and point me in the right
direction. The code is in the bottom of this post:
Thanks :)
---ooo---
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace MyTest
{
/// <summary>
/// Have all configuration options in it
/// </summary>
[Serializable]
public class Config
{
public Groups groups = new Groups();
public Config()
{
Serialize();
Deserialize();
}
private void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
groups.Add(new Groups.Group("test1"));
groups.Add(new Groups.Group("test2"));
groups.Add(new Groups.Group("test3"));
// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream(@"C:\DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the
stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, groups);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
private void Deserialize()
{
// Declare the groups reference.
groups = null;
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream(@"C:\DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
groups = (Groups) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (DictionaryEntry de in groups)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
}
}
public class Groups : Hashtable
{
public virtual void Add(Group group)
{
//forward our Add method on to the standard hashtable add method
base.Add(group.getKey(),group);
}
//this is the indexer (readonly)
public virtual new Group this[object key]
{
get
{
//return the Group at IList[Index]
return (Group)base[key];
}
}
public class Group
{
string key;
public Group(string arg)
{
key = arg;
}
public string getKey()
{
return key;
}
}
}
}
}