c# - 在应用程序设置中存储 Dictionary<string,string>

标签 c# .net-3.5 dictionary settings

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

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

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

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

最佳答案

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

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

生成的 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>
...

关于c# - 在应用程序设置中存储 Dictionary<string,string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/922047/

相关文章:

c# - 可以更新或删除的共享内存的线程安全枚举

C# listview 可点击的列和行

c# - 从相对路径获取绝对URL(重构方法)

c# - 是否可以通过 C#.NET 编写 Win32 .dll 文件?

c# - 使用 LINQ orderby 关键字与 OrderBy 扩展方法的等效排序

wpf - 虚拟化 WPF Wrap 面板问题

php - Python空字典和PHP

python - 存储列表字典的问题

c# - 以编程方式启用/禁用硬件设备

c# - Webreferences 共享类