今天做一个自动报表的功能,需要遍历某个目录下的所有的文件和文件夹,并在树上显示出来.

代码如下:

 private void GetFileInfo(string filePath, TreeNode node)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            try
            {
                foreach (DirectoryInfo childDirectoryInfo in directoryInfo.GetDirectories())
                {
                    TreeNode directoryNode = new TreeNode(childDirectoryInfo.Name.ToString());
                    directoryNode.Tag = childDirectoryInfo.Name.ToString();
                    GetFileInfo(filePath + "\\" + childDirectoryInfo.Name.ToString(), directoryNode);
                    node.Nodes.Add(directoryNode);
                }
                foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.html"))
                {
                    TreeNode leafNode = new TreeNode();
                    leafNode.Text = fileInfo.Name.ToString().Substring(0,fileInfo.Name.ToString().IndexOf(".html"));
                    leafNode.Tag = fileInfo.Name.ToString();
                    node.Nodes.Add(leafNode);
                }

 }
            catch
            {

            }
        }

使用介绍:

            TreeNode treenode = new TreeNode();
            treenode.Text = "报表树";
            GetFileInfo(@"C:\AutoReport", treenode);
            this.treeView1.Nodes.Add(treenode);

 

 

声明:

这段代码,只能够显示html的,如果您要使用,请视情况修改   foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.html"))
这个。。。。

 

posted on 2007-12-14 14:58  颜昌钢  阅读(2855)  评论(8编辑  收藏  举报