将文件夹层次显示在treeview控件中

private void Form1_Load(object sender, EventArgs e)
        {
            string rootpath = @"E:\config";
            DirectoryInfo dir = new DirectoryInfo(rootpath);
            TreeNode rootnode = new TreeNode();
            rootnode.Text = "任务列表";
            treeView1.Nodes.Add(rootnode);

            Recursion(dir, rootnode);
        }

        private void Recursion(DirectoryInfo dirParent, TreeNode tnParent)
        {
            DirectoryInfo[] dirarr = dirParent.GetDirectories();
            if (dirarr == null) return;//若无子文件夹则退出
            foreach (DirectoryInfo diri in dirarr)
            {
                TreeNode siteNode = new TreeNode();
                siteNode.Text = diri.Name;
                siteNode.Name = diri.FullName;
                tnParent.Nodes.Add(siteNode);

                Recursion(diri, siteNode);//递归
            }
        }
    }

posted on 2012-01-31 09:32  雨渐渐  阅读(213)  评论(0编辑  收藏  举报

导航