排除在树视图中显示某些文件夹和子文件夹

时间:2013-05-23 23:42:00

标签: c#

在我的一个驱动器上我有一个文件夹结构ex

d:\

123
    Code
        testfile.cs
    Database
        Backup.mdb
    Requirements
        Sprint1.xls

234
   20132305
        20132205
            20132105 
   Database  

我想在我的树视图中显示以下内容

d:\

123

    Code
        testfile.cs
    Database
        Backup.mdb 

234
   Database  

即仅显示“代码”和“数据库”的文件夹和子文件夹

以下是加载树视图的代码

folderLst = {“123”,“234”}

   private void PopulateTreeView()
    {
        TreeNode rootNode;
        foreach (string f in folderLst)
        {

            DirectoryInfo info = new DirectoryInfo(@"d:\");
            if (info.Exists)
            {
                rootNode = new TreeNode(info.Name);
                rootNode.Tag = info;
                GetDirectories(info.GetDirectories(), rootNode);
                treeView1.Nodes.Add(rootNode);
            }
        }
    }


  private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo)
    {
        TreeNode aNode;
        DirectoryInfo[] subSubDirs;
        foreach (DirectoryInfo subDir in subDirs)
        {
            aNode = new TreeNode(subDir.Name, 0, 0);
            aNode.Tag = subDir;

            subSubDirs = subDir.GetDirectories();
            if (subSubDirs.Length != 0)
            {
                GetDirectories(subSubDirs, aNode);
            }

            nodeToAddTo.Nodes.Add(aNode);
        }
    }

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您有以下代码

    foreach (DirectoryInfo subDir in subDirs)
    {
        aNode = new TreeNode(subDir.Name, 0, 0);
        aNode.Tag = subDir;

        subSubDirs = subDir.GetDirectories();
        if (subSubDirs.Length != 0)
        {
            GetDirectories(subSubDirs, aNode);
        }

        nodeToAddTo.Nodes.Add(aNode);
    }

您可以将其修改为不添加所需的文件夹

    foreach (DirectoryInfo subDir in subDirs)
    {
        if(subDir.Name.Contains("Code") || subDir.Name.Contains("Database"))
        {
            aNode = new TreeNode(subDir.Name, 0, 0);
            aNode.Tag = subDir;

            subSubDirs = subDir.GetDirectories();
            if (subSubDirs.Length != 0)
            {
                GetDirectories(subSubDirs, aNode);
            }

            nodeToAddTo.Nodes.Add(aNode);
        }
    }