Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从树视图保存节点_C#_Treeview - Fatal编程技术网

C# 从树视图保存节点

C# 从树视图保存节点,c#,treeview,C#,Treeview,我在windows应用程序中使用treeview控件。在这个应用程序中,有一个按钮可以添加几个节点(根节点和子节点)。现在我想保存这个结构,并在再次打开应用程序时使用它 我怎样才能做到这一点?您需要做以下几件事 1-使用BinaryFormatter序列化树结构,作为起点,请参见下文 private Byte[] SerilizeQueryFilters() { BinaryFormatter bf = new BinaryFormatter(); Tr

我在windows应用程序中使用treeview控件。在这个应用程序中,有一个按钮可以添加几个节点(根节点和子节点)。现在我想保存这个结构,并在再次打开应用程序时使用它


我怎样才能做到这一点?

您需要做以下几件事

1-使用BinaryFormatter序列化树结构,作为起点,请参见下文

private Byte[] SerilizeQueryFilters()
    {
        BinaryFormatter bf = new BinaryFormatter();

        TreeNodeCollection tnc = treeView1.Nodes;

        List<TreeNode> list = new List<TreeNode>();
        list.Add(treeView1.Nodes[0]);


        using (MemoryStream ms = new MemoryStream())
        {
            bf.Serialize(ms, list);
            return ms.GetBuffer();

        }


    }
private Byte[]SerilizeQueryFilters()
{
BinaryFormatter bf=新的BinaryFormatter();
TreeNodeCollection tnc=树视图1.节点;
列表=新列表();
list.Add(treeView1.Nodes[0]);
使用(MemoryStream ms=new MemoryStream())
{
bf.序列化(ms,列表);
返回ms.GetBuffer();
}
}
2-获得字节数组后,可以将其保存到数据库或文件中

3-当您想要重新创建树时,如果保存的数据在数据库中,则需要对其进行反序列化,读取字节[]数组中的实际字节和strore,或者如果它在文件中,则需要加载文件并将所有字节读取到字节数组中

4-当您得到实际字节时,您可以按照下面的代码进行反序列化

 private void DeSerilizeQueryFilters(byte[] items)
    {
        BinaryFormatter bf = new BinaryFormatter();

        List<TreeNode> _list = new List<TreeNode>();

        try
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(items, 0, items.Length);
                ms.Position = 0;

                _list = bf.Deserialize(ms) as List<TreeNode>;



            }


        }
        catch (Exception ex)
        {
        }




    }
private void反序列化查询过滤器(字节[]项)
{
BinaryFormatter bf=新的BinaryFormatter();
列表_List=新列表();
尝试
{
使用(MemoryStream ms=new MemoryStream())
{
ms.Write(items,0,items.Length);
ms.Position=0;
_列表=bf。反序列化(ms)为列表;
}
}
捕获(例外情况除外)
{
}
}
在这里您可以看到_列表将包含先前序列化的实际根节点,现在您获得了数据,您可以重新构建树