I have a dictionary of strings that i want the user to be able to add/remove info from then store it for them so it they can access it the next time the program restarts
I am unclear on how i can store a dictionary as a setting. I see that under system.collections.special there is a thing called a stringdictionary but ive read that SD are outdated and shouldn't be used.
also in the future i may have need to store a dictionary that is not strings only (int string)
how would you store a dictionary in the settings file for a .net application?
If you really want to store the full dictionary as a single string, then you could serialize your dictionary to JSON (or XML) and store the result to the database.
Add elements to a C# Dictionary Both types are generic so it can be any . NET data type. The following Dictionary class is a generic class and can store any data type. This class is defined in the code snippet creates a dictionary where both keys and values are string types.
One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.
You can use this class derived from StringDictionary. To be useful for application settings it implements IXmlSerializable. Or you can use similar approach to implement your own XmlSerializable class.
public class SerializableStringDictionary : System.Collections.Specialized.StringDictionary, System.Xml.Serialization.IXmlSerializable { public System.Xml.Schema.XmlSchema GetSchema() { return null; } public void ReadXml(System.Xml.XmlReader reader) { while (reader.Read() && !(reader.NodeType == System.Xml.XmlNodeType.EndElement && reader.LocalName == this.GetType().Name)) { var name = reader["Name"]; if (name == null) throw new FormatException(); var value = reader["Value"]; this[name] = value; } } public void WriteXml(System.Xml.XmlWriter writer) { foreach (System.Collections.DictionaryEntry entry in this) { writer.WriteStartElement("Pair"); writer.WriteAttributeString("Name", (string)entry.Key); writer.WriteAttributeString("Value", (string)entry.Value); writer.WriteEndElement(); } } }
Resulting XML fragment will look similar to:
... <setting name="PluginSettings" serializeAs="Xml"> <value> <SerializableStringDictionary> <Pair Name="property1" Value="True" /> <Pair Name="property2" Value="05/01/2011 0:00:00" /> </SerializableStringDictionary> </value> </setting> ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With