使用 WinForms TreeView 递归目录列表?
我想制作一个树视图,显示系统上的所有文件夹,并且仅显示音乐文件,例如 .mp3 .aiff .wav 等。
我记得读过我需要使用递归函数或类似的东西。
I want to make a treeview that shows all folders on the system, and only shows music files, such as .mp3 .aiff .wav etc.
I remember reading that I need to use a recursive function or something along those lines.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常大多数计算机都有数千个文件夹和数十万个文件,因此以递归方式在 TreeView 中显示所有这些文件非常慢并且消耗大量内存,请在 这个问题,引用我的答案并进行一些修改,何时可以获得一个非常可用的 GUI:
Usually most computers have thousands of folders and hundreds of thousands of files, so displaying all of them in a TreeView recursively with be very slow and consume a lot of memory, view my answer in this question, citing my answer with some modifications when can get a pretty usable GUI:
递归地搜索所有驱动器中的特定文件效果不佳。对于今天的大型驱动器来说,完成此操作大约需要一分钟。
Windows 资源管理器使用的一种标准技巧是仅列出顶级目录和文件。它将虚拟节点放入目录节点中。当用户打开节点(BeforeExpand 事件)时,它仅搜索该目录并用在该目录中找到的目录和文件替换虚拟节点。再次在目录中放置一个虚拟节点。等等。
您可以通过添加一个空子目录来查看它的工作情况。目录节点将用 + 字形显示。当您打开它时,资源管理器发现没有要列出的目录或文件,并删除了虚拟节点。 + 字形消失。
这非常快,列出单个目录的内容只需不到一秒。但是,在您的情况下使用这种方法存在问题。目录包含合适的音乐文件的可能性很小。用户会经常因为发现浏览一组子目录没有产生任何结果而感到沮丧。
这就是 Windows 有一个专门的位置来存储特定媒体文件的原因。在这种情况下我的音乐。使用Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) 来查找它。迭代它应该不会花很长时间。
Recursively searching all drives for particular files is not going to work well. It will take about a minute to do so with today's large drives.
One standard trick, used by Windows Explorer, is to only list the top level directories and files. It puts a dummy node in a directory node. When the user opens the node (BeforeExpand event), it searches only that directory and replaces the dummy node with the directories and files found it that directory. Again putting a dummy node in the directories. Etcetera.
You can see this at work by adding an empty subdirectory. The directory node will be shown with the + glyph. When you open it, Explorer discovers that there are no directory or files to be listed and deletes the dummy node. The + glyph disappears.
This is very fast, listing the content of a single directory takes well less than a second. There's a problem however using this approach in your case. The odds that a directory contains a suitable music file are small. The user will constantly be frustrated by finding out that the navigating through a set of subdirectories produces nothing.
That's why Windows has a dedicated place to store specific media files. My Music in this case. Use Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) to find it. Iterating it should not take long.