Ken'ichi Matsuyama
Ken'ichi Matsuyama

Reputation: 369

Save dictionary in application settings and load it on start

I've got Dictionary<string, double> which I would like to save and restore it when I restart the application. From what I have heard you cannot store dictionary in c#, so trying to make a workaround.

Currently I have made string variable in setting called DB, and trying to use something like this:

var settings = dict.ToArray();

var prop = Properties.Settings.Default.DB;

and make something like prop = settings;

Thus far I have done this, although it is now working..

private void SaveSettings()
{
    var settings = spamPercentage.ToArray();

    var prop = Properties.Settings.Default.DB;

    string res = String.Join(",", settings);

    prop = res;
}

private void LoadSettings()
{
    var prop = Properties.Settings.Default.DB;

    var dictionary = prop.ToDictionary(item => item.Key,
                               item => item.Value);
}

edit Values in dictionary looks like this:

{[john, 0,53]}
{[ivone, 0,44]}
etc.

@edit Using Julien JSON idea, I have made:

 string prop = Properties.Settings.Default.DB;
    private void SaveSettings()
    {

        prop = JsonConvert.SerializeObject(dict);
Properties.Settings.Default.Save();
    }

    private void LoadSettings()
    {
        dict= JsonConvert.DeserializeObject<Dictionary<string, double>>(prop);
    }

When I hit program, and use my SaveSettings method, I can see that it has values. Then I reboot program, and try loadsettings and they are null.

Upvotes: 3

Views: 7082

Answers (2)

blindmeis
blindmeis

Reputation: 22445

i use this to store my datagrid settings in wpf

[XmlRoot("Dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{

    #region IXmlSerializable Members
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        var keySerializer = new XmlSerializer(typeof(TKey));
        var valueSerializer = new XmlSerializer(typeof(TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;

        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");

            reader.ReadStartElement("key");
            var key = (TKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            var value = (TValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            this.Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        var keySerializer = new XmlSerializer(typeof(TKey));
        var valueSerializer = new XmlSerializer(typeof(TValue));

        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("item");

            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
    }
    #endregion
}

settings:

[SettingsManageabilityAttribute(SettingsManageability.Roaming)]
public abstract class GridSettingsBase : ApplicationSettingsBase, IGridSettings
{
    [UserScopedSettingAttribute()]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(SettingsSerializeAs.Xml)]
    public SerializableDictionary<string, int> GridDisplayIndexList
    {
        get { return (SerializableDictionary<string, int>)this["GridDisplayIndexList"]; }
        set { this["GridDisplayIndexList"] = value; }
    }

    [UserScopedSettingAttribute()]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(SettingsSerializeAs.Xml)]
    public SerializableDictionary<string, Visibility> GridColumnVisibilityList
    {
        get { return (SerializableDictionary<string, Visibility>)this["GridColumnVisibilityList"]; }
        set { this["GridColumnVisibilityList"] = value; }
    }

    [UserScopedSettingAttribute()]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(SettingsSerializeAs.Xml)]
    public SerializableDictionary<string, double> GridColumnWidthList
    {
        get { return (SerializableDictionary<string, double>)this["GridColumnWidthList"]; }
        set { this["GridColumnWidthList"] = value; }
    }

    [UserScopedSettingAttribute()]
    [DefaultSettingValue("")]
    [SettingsSerializeAs(SettingsSerializeAs.Xml)]
    public List<SortDescription> GridSortDescriptionList
    {
        get { return (List<SortDescription>)this["GridSortDescriptionList"]; }
        set { this["GridSortDescriptionList"] = value; }
    }

    protected GridSettingsBase()
    {
        Application.Current.Exit += OnExit;
    }

    private void OnExit(object sender, ExitEventArgs e)
    {
        this.Save();
    }
}

Upvotes: 4

Julien
Julien

Reputation: 263

I had a similar problem a while ago. I ended up using JSON Serialization to serialize the Dictionary as a string, store it in the application settings, and deserialize it back to a Dictionary when I needed it.

string strDictionaryAsString = JsonConvert.SerializeObject(dtnDictionary);

var dtnDictionary = JsonConvert.DeserializeObject<Dictionary<string, double>>(strDictionaryAsString );

Upvotes: 11

Related Questions