今天做一個自動報表的功能,需要遍曆某個目錄下的所有的檔案和檔案夾,並在樹上顯示出來.
代碼如下:
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"))
這個。。。。