Hello,
In .NET you can select a hashtable as type for a usersetting. However when I save it and retrieve it in this way, it doesnt seem to have saved it at all.
Hashtable t = new Hashtable();
t.Add(1,"Foo");
t.Add(2,"Bar");
Properties.Settings.Default.Setting = t;
Properties.Settings.Default.Save();
if(Properties.Settings.Default.Setting != null)
foreach (DictionaryEntry entry in Properties.Settings.Default.Setting)
{
MessageBox.Show(entry.Key + " " + entry.Value);
}
Why doesnt it serialize it in the usersettings, when I can clearly select that type in Visual studio? I would understand if this was the case with an unlisted type such as dictionary, but Hashtable is listed. How do I solve this problem?
Simplicity and efficiency in this order have the highest priority for me.
Many Thanks, Kave
update:
@Joao , Many Thanks the Binary solution. I find it quite interesting, its clean. One disadvavtage with serializing it as binary might be the fact that you cant change anything in the usersetting file manually anymore. but I think that will be done very rarely anyway, so its a good solution.
I was thinking of a different approach to create an "XMLSetting" field of type string in the user scope and use this code to store and retrieve the values as an XMl file serialized into a hashtable. But I am sure this is not the best way, does anyone know a better way to serialize a hashtable/dictionary as xml in the usersettings, other than what i am doing below?
if(string.IsNullOrEmpty(Properties.Settings.Default.XMLSetting))
{
Console.WriteLine("Usersettings is empty. Initializing XML file...");
XmlDocument doc = new XmlDocument();
XmlElement hashtable = doc.CreateElement("HashTable");
doc.AppendChild(hashtable);
GenerateValues(doc, hashtable, "1", "Foo");
GenerateValues(doc, hashtable, "2", "Bar");
Properties.Settings.Default.XMLSetting = doc.OuterXml;
Properties.Settings.Default.Save();
}
else
{
Console.WriteLine("Retrieving existing user settings...");
XmlDocument doc = new XmlDocument();
doc.LoadXml(Properties.Settings.Default.XMLSetting);
Hashtable hashtable = new Hashtable();
foreach (XmlNode entry in doc.DocumentElement.ChildNodes)
{
hashtable.Add(int.Parse(entry.FirstChild.InnerText), entry.FirstChild.NextSibling.InnerText);
}
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine(entry.Key + " " + entry.Value);
}
}
private static void GenerateValues(XmlDocument doc, XmlElement hashtable, string skey, string svalue)
{
XmlElement entry = doc.CreateElement("entry");
XmlElement key = doc.CreateElement("Key");
XmlElement value = doc.CreateElement("Value");
entry.AppendChild(key);
entry.AppendChild(value);
key.AppendChild(doc.CreateTextNode(skey));
value.AppendChild(doc.CreateTextNode(svalue));
hashtable.AppendChild(entry);
}