Save the contents of the tree to a file and load it later.

In my C # WinForms program, I have a tree that contains only the parent nodes (so there are no children) this looks like a list, but I need it because of the presence of properties of different types of nodes, such as Name, Tag and Text.

Not. I want to save the contents of this tree to a file (basically a text file, which I call * .MVIA). The question is, what is the best way to save all three properties of nodes in a file so that it can load later later?

At the moment, I came up with this idea:

private void menuFileSave_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); foreach(TreeNode node in treeViewFiles.Nodes) { sb.AppendLine(node.Name); } SaveFileDialog saveList = new SaveFileDialog(); saveList.DefaultExt = "*.mvia"; saveList.Filter = "MVIA Files|*.mvia"; if (saveList.ShowDialog() == DialogResult.OK) { File.WriteAllText(saveList.FileName, sb.ToString()); } } 

As you can see, each Name property of each node will be stored in a string. Now I need to add the Text and Tag property, but later I can not read it (to be honest, I do not know how to do this).

Could you give me some ideas that it is best to save all three properties of each node and you can easily load it later?

Thanks.

+8
c # serialization winforms treeview
source share
1 answer

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); } } 
+17
source share

All Articles