将树视图的内容保存到文件并稍后加载 [英] Saving content of a treeview to a file and load it later

查看:23
本文介绍了将树视图的内容保存到文件并稍后加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 C# WinForms 程序中,我有一个仅包含父节点(因此,没有子节点)的树视图,它就像一个列表框,但我需要它,因为它具有不同的节点属性,如名称、标签和文本.

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?

此刻我有了这个想法:

    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 属性都会保存在一行中.现在我还需要添加它的 Text 和 Tag 属性,但后来我无法读取它(老实说我不知道​​如何).

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);
        }
    }

这篇关于将树视图的内容保存到文件并稍后加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆