Saving content of a treeview to a file and load it later

前端 未结 1 1565
说谎
说谎 2020-12-03 02:16

In my C# WinForms program I have a treeview that only contains parent nodes (so, no childs) it is like a listbox but I needed it because of haveing differet properties of no

相关标签:
1条回答
  • 2020-12-03 02:41

    You can use BinaryFormatter to Serialize/Deserialize Nodes

        public static void SaveTree(TreeView tree, string filename)
        {
            using (Stream file = File.Open(filename, FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(file, tree.Nodes.Cast<TreeNode>().ToList());
            }
        }
    
        public static void LoadTree(TreeView tree, string filename)
        {
            using (Stream file = File.Open(filename, FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                object obj = bf.Deserialize(file);
    
                TreeNode [] nodeList = (obj as IEnumerable<TreeNode>).ToArray();
                tree.Nodes.AddRange(nodeList);
            }
        }
    
    0 讨论(0)
提交回复
热议问题