如何将toolstripmenuitem项目/集合保存/加载到properties.default.settings? (C#)

发布于 2024-12-14 13:45:40 字数 106 浏览 3 评论 0原文

我如何在 C# 中将toolstripmenuitem 项目/集合保存/加载到properties.default.settings? 或者序列化为xml?我必须使用什么类型的列表? 比你,安德烈斯

how i can to save/load toolstripmenuitem items/collection to properties.default.settings in c#?
Or serialize to xml? What type of list I have to use?
than you, Andrius

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

趴在窗边数星星i 2024-12-21 13:45:40

那么,您可以使用 Name 和 Text 属性创建简单的可序列化类,填充列表和序列化/反序列化列表,如下所示:

private XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<MySaveItems>));
private void SerializeToFile()
{
    using (MemoryStream ms = new MemoryStream(5 * 1024))
    {
        List<MySaveItems> mySaveItemses = new List<MySaveItems>();
        foreach (ToolStripItem item in toolStrip1.Items)
        {
            MySaveItems mySaveItem = new MySaveItems();
            mySaveItem.name = item.Name;
            mySaveItem.text = item.Text;
            mySaveItemses.Add(mySaveItem);
        }
        xmlSerializer.Serialize(ms, mySaveItemses);
        File.WriteAllBytes("c:\\ToolStripItems.xml", ms.ToArray());
    }
}

private void DeserializeFromFile()
{
    using (StreamReader ms = new StreamReader("c:\\ToolStripItems.xml"))
    {
        List<MySaveItems> mySaveItemses;
        mySaveItemses = (List<MySaveItems>)xmlSerializer.Deserialize(ms);
    }
}

[Serializable]
public class MySaveItems
{
    public MySaveItems()
    {

    }

    [XmlElement]
    public string name { get; set; }
    [XmlElement]
    public string text { get; set; }
}

Well you can create simple serializable class with Name and Text properties, fill list and serialize/deserialize list like so:

private XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<MySaveItems>));
private void SerializeToFile()
{
    using (MemoryStream ms = new MemoryStream(5 * 1024))
    {
        List<MySaveItems> mySaveItemses = new List<MySaveItems>();
        foreach (ToolStripItem item in toolStrip1.Items)
        {
            MySaveItems mySaveItem = new MySaveItems();
            mySaveItem.name = item.Name;
            mySaveItem.text = item.Text;
            mySaveItemses.Add(mySaveItem);
        }
        xmlSerializer.Serialize(ms, mySaveItemses);
        File.WriteAllBytes("c:\\ToolStripItems.xml", ms.ToArray());
    }
}

private void DeserializeFromFile()
{
    using (StreamReader ms = new StreamReader("c:\\ToolStripItems.xml"))
    {
        List<MySaveItems> mySaveItemses;
        mySaveItemses = (List<MySaveItems>)xmlSerializer.Deserialize(ms);
    }
}

[Serializable]
public class MySaveItems
{
    public MySaveItems()
    {

    }

    [XmlElement]
    public string name { get; set; }
    [XmlElement]
    public string text { get; set; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文