如何保存/加载toolstripmenuitem项/集合到properties.default.settings?(c#

本文关键字:properties default settings 集合 toolstripmenuitem 何保存 保存 加载 | 更新日期: 2023-09-27 18:13:58

如何在c#中保存/加载toolstripmenuitem项/集合到properties.default.settings ?或者序列化为xml?我必须使用什么类型的列表?

如何保存/加载toolstripmenuitem项/集合到properties.default.settings?(c#

你可以创建一个简单的具有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; }
}