当先锋百科网

首页 1 2 3 4 5 6 7

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

代码如下:

 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);