保存一个TreeView的内容到一个文件,以后加载 [英] Saving content of a treeview to a file and load it later
问题描述
在我的C#的WinForms程序我有一个只包含父节点(所以,没有孩子的)一个TreeView它像一个列表框,但我需要它,因为巡航能力,如姓名,标签和文本节点的differet属性。
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 nodes like Name, Tag and Text.
没有我希望能够到这个树状的内容保存到一个文件中(基本上是一个文本文件,我把它叫做* .MVIA)。问题是什么是节约节点的所有三个属性中的一个文件,以便它可以再次加载的最佳方式后是否正确?
No I want to be able to save the content of this treeview into a file (Basically a text file which I call it *.MVIA). The question is what is the best way to save all three properties of nodes in a file so it can loaded again later properly?
在我来到这个想法的时刻:
At the moment I came 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());
}
}
正如你所看到的,每个节点的每个Name属性将被保存在一条线上。现在我还需要添加它的文本和标签属性,但后来我有麻烦回读(老实说,我不知道如何)。
As you can see, each Name property of each node will be saved in a line. Now I need to add its Text and Tag property also, but later I have trouble reading it back (Honestly I don't know how to).
你能给我一些想法是什么,以节省每一个节点的全部三个属性,并且能够很容易地加载一个最好的办法以后呢?
Would you give me some ideas what is a best way to save all three property of each node and be able to load it easily later?
感谢。
推荐答案
您可以使用BinaryFormatter的序列化到/反序列化的节点
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);
}
}
这篇关于保存一个TreeView的内容到一个文件,以后加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!