从类似路径的字符串生成TreeView层次结构 - C#.NET

时间:2014-02-19 13:35:01

标签: c# recursion treeview hierarchy

在我的程序中,用户使用元数据标记文件,他可以从有限且已知数量的框中选择(假设框是年,月和日)。然后将文件移动到通过组合所选数据创建的路径中。

我希望用户能够在程序设置中指定如何通过字符串创建路径,例如

[ROOT] \%year%\%month%\%day%

或三者的任何其他组合。他应该能够根据需要指定尽可能多的子级别。

现在,我有一个TreeView控件,我想根据用户选择的配置字符串显示常规文件夹结构的预览,无论该文件夹是否已存在。

我希望每年的文件夹都包含所有月份的子文件夹,并且每个月的子文件夹都包含全天子文件夹(忽略不同月份的实际日期计数,这只是一个示例)

现在我的列表中包含年,月和日的值,以及将每个列表链接到字符串及其名称的字典:

public partial class Form1 : Form
{
    string StructureString = @"year\month\day";
    string[] StructureArray = StructureString.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

    List<string> year = new List<string>() {"2014", "2013", "2012"};
    List<string> month = new List<string>() {"January", "February", ... , "December"};
    List<string> day = new List<string>() {"1", "2", ... , "31"};

    Dictionary<string, List<string>> StructureData = new Dictionary<string, List<string>>();
}

public Form1()
{
    InitializeComponent();  // Designer code
    InitializeData();
    PopulateTreeView();
}

private InitializeData()
{
    StructureData.Add("year", year);
    StructureData.Add("month", month);
    StructureData.Add("day", day);
}

现在,我知道我必须在这里使用递归,并且我已经设法有一个TreeView,它通过文件系统中的现有子目录进行分类。但我不知道如何继续这里。

我正在尝试类似的事情:

    int i = 0;

    private void PopulateTreeView()
    {
        treeView1.Nodes.Add(AddSubNode(i));
    }

    private TreeNode AddSubNode(int level)
    {
        TreeNode tn = new TreeNode();

        foreach (string s in StructureData[StructureArray[i]])
        {
          if (i < StructureArray.Length)
          {
              tn.Nodes.Add(AddSubNode(i + 1));
          }
        }
        i++;

        return tn;
    }

但是我收到了StackOverflowException。而且,一般来说,我甚至不确定我在这里编码是否有意义。任何帮助我做正确方向的帮助都会非常赞赏。

谢谢!

1 个答案:

答案 0 :(得分:0)

有些用户回答了我的问题,在删除自己的答案之前,我设法复制了代码。它有一些问题(一个错误的变量名称 - 正如LarsTech指出的那样 - 节点是空白的)但是我能够调整他的解决方案并得出所需的结果。

我将其作为具有相同问题的其他人的答案发布。

private void PopulateTreeView()
{
    treeView1.Nodes.Add(AddSubNode(0, new TreeNode("Root")));
}

private TreeNode AddSubNode(int level, TreeNode hierarchy)
{
    if (level == StructureArray.Length)
    {
        return hierarchy;
    }

    foreach (string s in StructureData[StructureArray[i]])
    {
        tn.Nodes.Add(AddSubNode(level + 1, new TreeNode(s)));
    }
    return tn;
}

要自定义节点属性(text,tag,images ...),而不是键入“new Treenode()”作为函数参数,请事先声明TreeNode对象,然后设置其属性,最后将其用作函数参数。