遍历文件夹、文件的目录树
想学习一下编一个遍历文件夹、文件的目录树,怎么入手解决?
可以先详细了解一下 C#文件IO操作 和如何在C#中使用命名空间访问目录和文件
程序代码: private TreeNode CreateDirNode(string fullPath)
{
/*检查Path是否存在*/
if (Directory.Exists(fullPath))
{
DirectoryInfo currentDirPath = new DirectoryInfo(fullPath);
TreeNode dirNode = new TreeNode(fullPath, 0, 0);
if (currentDirPath.GetDirectories().Length >= 1)
{
/*递归当前目录下的文件夹*/
foreach (DirectoryInfo dirInfo in currentDirPath.GetDirectories())
{
dirNode.Nodes.Add(CreateDirNode(dirInfo.FullName));
}
}
/*创建当前目录下所有的文件*/
List<TreeNode> nodes = new List<TreeNode>();
foreach (FileInfo fileInfo in currentDirPath.GetFiles())
{
TreeNode trnd = new TreeNode(fileInfo.Name, 1, 1);
nodes.Add(trnd);
}
foreach (TreeNode tn in nodes)
{
dirNode.Nodes.Add(tn);
}
return dirNode;
}
else
{
throw new Exception("Error! \"" + fullPath + "\" is not exisit!\r\n");
}
}
}