gpt4 book ai didi

c# - 使用 WinForms TreeView 的递归目录列表?

转载 作者:太空狗 更新时间:2023-10-29 22:07:43 25 4
gpt4 key购买 nike

我想制作一个显示系统上所有文件夹的 TreeView ,并且只显示音乐文件,例如 .mp3 .aiff .wav 等

我记得读过我需要使用递归函数或类似的东西。

最佳答案

通常大多数计算机都有数千个文件夹和数十万个文件,因此递归地在 TreeView 中显示所有这些非常慢并且消耗大量内存,请查看我在 this question 中的回答。 ,引用我的答案并进行一些修改何时可以获得非常有用的 GUI:

// Handle the BeforeExpand event
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Tag != null) {
AddDirectoriesAndMusicFiles(e.Node, (string)e.Node.Tag);
}
}

private void AddDirectoriesAndMusicFiles(TreeNode node, string path)
{
node.Nodes.Clear(); // clear dummy node if exists

try {
DirectoryInfo currentDir = new DirectoryInfo(path);
DirectoryInfo[] subdirs = currentDir.GetDirectories();

foreach (DirectoryInfo subdir in subdirs) {
TreeNode child = new TreeNode(subdir.Name);
child.Tag = subdir.FullName; // save full path in tag
// TODO: Use some image for the node to show its a music file

child.Nodes.Add(new TreeNode()); // add dummy node to allow expansion
node.Nodes.Add(child);
}

List<FileInfo> files = new List<FileInfo>();
files.AddRange(currentDir.GetFiles("*.mp3"));
files.AddRange(currentDir.GetFiles("*.aiff"));
files.AddRange(currentDir.GetFiles("*.wav")); // etc

foreach (FileInfo file in files) {
TreeNode child = new TreeNode(file.Name);
// TODO: Use some image for the node to show its a music file

child.Tag = file; // save full path for later use
node.Nodes.Add(child);
}

} catch { // try to handle use each exception separately
} finally {
node.Tag = null; // clear tag
}
}

private void MainForm_Load(object sender, EventArgs e)
{
foreach (DriveInfo d in DriveInfo.GetDrives()) {
TreeNode root = new TreeNode(d.Name);
root.Tag = d.Name; // for later reference
// TODO: Use Drive image for node

root.Nodes.Add(new TreeNode()); // add dummy node to allow expansion
treeView1.Nodes.Add(root);
}
}

关于c# - 使用 WinForms TreeView 的递归目录列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2263013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com