设置文件中的键值存储

时间:2009-07-22 16:25:40

标签: c#

我正在用C#开发一个应用程序,它需要在设置文件中存储一个键值对。 我尝试在设置文件中保存字典的arraylist,但它失败了。这就是我所做的:

if (Settings1.Default.arraylst == null)
       {
           Settings1.Default.arraylst = new System.Collections.ArrayList();
       }

       Dictionary<string, string> dd = new Dictionary<string, string>();
       dd.Add("1", "1");

       Settings1.Default.arraylst.Add(dd);              
       Settings1.Default.Save();

当我重新启动应用程序时,arrarylist变为null ..

提前致谢....

2 个答案:

答案 0 :(得分:4)

这是因为泛型字典由于某些原因不可序列化,请尝试使用此字典

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

[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)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer 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");
            TKey key = (TKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();
            reader.ReadStartElement("value");
            TValue value = (TValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();
            this.Add(key, value);
            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }
    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer 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
}

我在这里找到XML Serializable Generic Dictionary

答案 1 :(得分:1)

C#设置文件只是XML文件,只保存可序列化的类,否则保存时不会写出数据。遗憾的是,词典不可序列化。

一种解决方案是构建自己的包装器,以正确序列化字典。 This link可能会让您知道这涉及到什么。

另一个解决方案是将键/值对写为长字符串数组,并在重新读取时解析它。

//Define a string[] in your settings

List<string> keyValues = new List<string>();
foreach(KeyValuePair<string,string> pair in dd)
{
  keyValues.Add(pair.Key);
  keyValues.Add(pair.Value);
}
Settings1.Default.KeyValuePairs = keyValues.ToArray();

然后在以类似方式加载时回读对。