在应用程序设置中存储字典<string,string>

Cra*_*893 33 c# settings dictionary .net-3.5

我有一个字符串字典,我希望用户能够添加/删除信息然后存储它们,以便他们可以在下次程序重新启动时访问它

我不知道如何将字典存储为设置.我看到在system.collections.special下有一个叫做stringdictionary的东西,但我读过SD已经过时了,不应该使用它.

同样在将来我可能需要存储一个不仅仅是字符串的字典(int string)

如何在.net应用程序的设置文件中存储字典?

Vse*_*nov 43

您可以使用从StringDictionary派生的此类.为了对应用程序设置有用,它实现了IXmlSerializable.或者您可以使用类似的方法来实现自己的XmlSerializable类.

public class SerializableStringDictionary : StringDictionary, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        while (reader.Read() &&
            !(reader.NodeType == 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(XmlWriter writer)
    {
        foreach (DictionaryEntry entry in this)
        {
            writer.WriteStartElement("Pair");
            writer.WriteAttributeString("Name", (string)entry.Key);
            writer.WriteAttributeString("Value", (string)entry.Value);
            writer.WriteEndElement();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

生成的XML片段看起来类似于:

...
<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>
...
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么这个答案不被接受.非常有用,谢谢! (3认同)
  • 为我工作,但我将`this.Clear();`语句添加到ReadXml方法的顶部,只是为了确保字典中没有任何陈旧的项目. (3认同)
  • 对此有任何设计师支持吗? (2认同)

Dav*_*vid 16

最简单的答案是使用行和列分隔符将字典转换为单个字符串.然后你只需要在设置文件中存储1个字符串.

  • 好主意 - 使用类似JSON序列化的东西来使这个过程相对轻松. (5认同)
  • 类似但更简单的是使用StringCollection(可以存储为设置).然后,您只需要将键与值分开(不要使用'\ 0' - .Net设置代码很高兴保存StringCollection设置条目,其中包含零字节但稍后不会加载它). (4认同)