[C#]TreeView实现文件结构查看器

xiaoxiao2021-02-27  158

最近学习Android想对于Android的项目结构研究研究,但是一级级目录点进去实在是太麻烦了,就想自己写一个文件结构查看器。

大体思路:

1.遍历文件夹下文件和文件夹,把当前的文件/文件夹的名字添加到一个节点

2.判断如果是文件,则遍历下一个文件,如果是文件夹则重复1步骤。

private void createNodes(String rootFile, TreeNode rootNode) { DirectoryInfo dInfo = new DirectoryInfo(rootFile); //遍历当前文件系统下的所有文件和文件夹 foreach (FileSystemInfo info in dInfo.GetFileSystemInfos()) { TreeNode node = new TreeNode(); node.Text = info.Name; rootNode.Nodes.Add(node); //文件夹 String file = info.FullName; if(Directory.Exists(file)) { createNodes(file, node); } } }

程序运行效果:

程序源代码:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace VisualFiles { public partial class Main : Form { public Main() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { } private void clearButton_Click(object sender, EventArgs e) { textBox.Text = ""; treeView.Nodes.Clear(); } private void doButton_Click(object sender, EventArgs e) { String rootFile = textBox.Text.ToString().Trim(); if (!Directory.Exists(rootFile)) { MessageBox.Show("文件夹位置错误!"); } else { //根节点 TreeNode rootNode = new TreeNode(); rootNode.Text = rootFile; //递归创建节点 createNodes(rootFile, rootNode); //TreeView treeView.Nodes.Add(rootNode); treeView.ExpandAll(); } } private void createNodes(String rootFile, TreeNode rootNode) { DirectoryInfo dInfo = new DirectoryInfo(rootFile); //遍历当前文件系统下的所有文件和文件夹 foreach (FileSystemInfo info in dInfo.GetFileSystemInfos()) { TreeNode node = new TreeNode(); node.Text = info.Name; rootNode.Nodes.Add(node); //文件夹 String file = info.FullName; if(Directory.Exists(file)) { createNodes(file, node); } } } } }

转载请注明原文地址: https://www.6miu.com/read-12816.html

最新回复(0)