python treeview写入文件,保存一个TreeView的内容到一个文件,以后加载

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.

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

}

}

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?

Thanks.

解决方案

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().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).ToArray();

tree.Nodes.AddRange(nodeList);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值