我试图将树视图转换为字节数组然后再返回。到目前为止,当表单加载时,它将加载我的文档的结构。然后据我所知它将它转换为字节数组并返回但我不知道如何将字节数组转换回树视图。这是我的代码
namespace tree_view
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
ListDirectory(treeView1, filepath);
}
private static void ListDirectory(TreeView treeView, string path)
{
treeView.Nodes.Clear();
var stack = new Stack<TreeNode>();
var rootDirectory = new DirectoryInfo(path);
var node = new TreeNode(rootDirectory.Name) { Tag = rootDirectory };
stack.Push(node);
while (stack.Count > 0)
{
var currentNode = stack.Pop();
var directoryInfo = (DirectoryInfo)currentNode.Tag;
foreach (var directory in directoryInfo.GetDirectories())
{
var childDirectoryNode = new TreeNode(directory.Name) { Tag = directory };
currentNode.Nodes.Add(childDirectoryNode);
stack.Push(childDirectoryNode);
}
foreach (var file in directoryInfo.GetFiles())
currentNode.Nodes.Add(new TreeNode(file.Name));
}
treeView.Nodes.Add(node);
}
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 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>;
treeView2 = _list;
}
}
catch { }
}
private void button1_Click(object sender, EventArgs e)
{
byte[] data = SerilizeQueryFilters();
DeSerilizeQueryFilters(data);
}
}
所以此刻给我错误的是“treeView2 = _list;”因为我“无法隐式转换类型System.collections.generic.List到System.Windows.Forms.TreeView”。有人有什么想法吗?
答案 0 :(得分:0)
在DeSerilizeQueryFilters()
方法中,您应该只需在TreeView的.AddRange()
集合上调用Nodes
,然后添加列表中的所有节点。
_list = bf.Deserialize(ms) as List<TreeNode>;
treeView2.Nodes.AddRange(_list.ToArray()); //The parameter needs to be an array.
修改强>
此外,在您的SerilizeQueryFilters()
方法中,您目前只将第一个TreeNode
添加到列表中。要添加所有节点,只需替换:
list.Add(treeView1.Nodes[0]);
使用:
foreach(TreeNode node in treeView1.Nodes)
{
list.Add(node);
}