c# winforms - 将树结构显示为制表符格式的文本

c# winforms - Display tree structure as tab formatted text

我需要将 treeView 结构导出为制表符格式的文本,如下所示:

node 1
   child node 1.1
      child node 1.1.1
         child node 1.1.1.1
node 2
   child node 2.1
      child node 2.1.1
         child node 2.1.1.1
...etc

我创建了以下递归例程:

     public static string ExportTreeNode(TreeNodeCollection treeNodes)
     {
        string retText = null;

        if (treeNodes.Count == 0) return null;

        foreach (TreeNode node in treeNodes)
        {
            retText += node.Text + "\n";

            // Recursively check the children of each node in the nodes collection.
            retText += "\t" + ExportTreeNode(node.Nodes);
        }
        return retText;
    }

希望它能完成这项工作,但事实并非如此。相反,它将树结构输出为:

node 1
   child node 1.1
   child node 1.1.1
   child node 1.1.1.1
   node 2
   child node 2.1
   child node 2.1.1
   child node 2.1.1.1

有人可以帮我解决这个问题吗?非常感谢!

你在这行所做的假设是不正确的:它只缩进了第一个子节点。

retText += "\t" + ExportTreeNode(node.Nodes);

此外,您的选项卡没有聚合 - 实际上左侧的选项卡永远不会超过一个。向您的函数添加一个缩进参数:

public static string ExportTreeNode(TreeNodeCollection treeNodes, string indent = "")

并更改

retText += node.Text + "\n";

// Recursively check the children of each node in the nodes collection.
retText += "\t" + ExportTreeNode(node.Nodes);

retText += indent + node.Text + "\n";

// Recursively check the children of each node in the nodes collection.
retText += ExportTreeNode(node.Nodes, indent + "\t");