C#读取文件夹树结构

NullWzc NullWzc 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
一级文件夹为主目录,1个,二级文件夹有好多个,三级文件夹有好多个,一直到8级文件夹,但是我只想读取到第5级文件夹,后面三级文件夹我不想读取出来。
代码如下,path为一级文件夹目录,怎么修改可以只读到5级文件夹就停止,而不是读完全部?(读出的结构是放在treeView里)
        
public void listTreeNode(string path)
{
List<TreeNode> list = new List<TreeNode>();
DirectoryInfo dirInfo = new DirectoryInfo(path);
FileSystemInfo[] dir = dirInfo.GetFileSystemInfos();
foreach (FileSystemInfo di in dir)
{
if (di.Attributes == (System.IO.FileAttributes.Hidden | System.IO.FileAttributes.System | System.IO.FileAttributes.Directory))
{
continue;
}
TreeNode treeNode = new TreeNode(di.Name, ListFiles(di).ToArray());
list.Add(treeNode);
}
TreeNode node = new TreeNode(path, list.ToArray());
treeView1.Nodes.Add(node);
node.Expand();
}

public List<TreeNode> ListFiles(FileSystemInfo fileinfo)
{
List<TreeNode> nodeList = new List<TreeNode>();
if (!fileinfo.Exists)
return null;
DirectoryInfo dirinfo = fileinfo as DirectoryInfo;
if (dirinfo == null)
return null;
FileSystemInfo[] files = dirinfo.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
DirectoryInfo subdir = files[i] as DirectoryInfo;
if (subdir == null)
{
continue;
}
TreeNode tnode = new TreeNode(subdir.Name, ListFiles(files[i]).ToArray());
nodeList.Add(tnode);
}
return nodeList;
}
...全文

相关推荐

评论 7
收藏 已收藏
分享
返回顶部
NullWzc
C# 111,128 成员 642,537 内容