private void button1_Click(object sender, EventArgs e)
{
//Directory/Folder目录
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
//ShowDialog对话框
if (folderBrowserDialog.ShowDialog()==DialogResult.OK)
{
//清除追加的效果
treeView1.Nodes.Clear();
//获取用户选定路径
string getPath=folderBrowserDialog.SelectedPath;
//实例化一个树节点
TreeNode rooNode = new TreeNode();
//在获取到的都换成空
rooNode.Text = getPath.Replace(Path.GetDirectoryName(getPath)+"\\", "");
//获取文件夹下的所有内容
string[] getStrings = Directory.GetFileSystemEntries(getPath);
//调用下面的方法
SearchDirectories(rooNode, getStrings);
//一级显示
treeView1.Nodes.Add(rooNode);
}
}
public void SearchDirectories(TreeNode treeNode,string[] Path)
{
for (int i = 0; i < Path.Length; i++)
{
//判断当前路径是否是目录
if(Directory.Exists(Path[i]))
{
TreeNode node = new TreeNode();
node.Text = Path[i];
string[] getStrings = Directory.GetFileSystemEntries(Path[i]);
SearchDirectories(node, getStrings);
treeNode.Nodes.Add(node);
}
else
{
//是文件
TreeNode tree = new TreeNode();
tree.Text = Path[i];
treeNode.Nodes.Add(tree);
}
}
}
原文地址:https://www.cnblogs.com/LLF123/p/11371566.html