在应用程序设置中保存字典并在启动时加载它

时间:2015-05-08 11:38:01

标签: c# wpf dictionary settings converter

我有Dictionary<string, double>我要保存并在重新启动应用程序时将其恢复。据我所知,你不能在c#中存储字典,所以试图解决方法。

目前我在名为DB的设置中创建了字符串变量,并尝试使用以下内容:

var settings = dict.ToArray();

var prop = Properties.Settings.Default.DB;

并制作类似prop = settings;

的内容

到目前为止,我已经做到了这一点,虽然它现在正在运作..

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);
}

编辑 字典中的值如下所示:

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

@edit 使用Julien JSON的想法,我做了:

 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);
    }

当我点击程序并使用我的SaveSettings方法时,我可以看到它有值。然后我重启程序,尝试加载设置,它们都是空的。

2 个答案:

答案 0 :(得分:7)

前一段时间我遇到过类似的问题。我最终使用JSON Serialization将字典序列化为字符串,将其存储在应用程序设置中,并在需要时将其反序列化为字典。

string strDictionaryAsString = JsonConvert.SerializeObject(dtnDictionary);

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

答案 1 :(得分:3)

我用它将我的数据网格设置存储在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
}

设置:

[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();
    }
}