Directory.GetFiles,如何让它在找到项目时吐出项目?
我正在使用 Directory.GetFiles
给我 mp3 文件,并且我想用结果填充 ListBox
,但不要在程序运行时停止程序该方法,我可以让它在获取 mp3 文件时搜索并填充 ListBox
吗?
所以我使用的是如下(它无法一次添加它们,而是在完成后一次添加它们)
private List<string> Getmp3sFromFolders(string folder)
{
List<string> fileArray = new List<string>();
try
{
DirectoryInfo dir = new DirectoryInfo(folder);
var files = dir.EnumerateFiles("*.mp3");
foreach (var file in files)
{
fileArray.Add(file.FullName);
Dispatcher.BeginInvoke(_AddMP3ToListbox, file.Name);
}
var directories = dir.EnumerateDirectories();
foreach (var subdir in directories)
{
fileArray.AddRange(Getmp3sFromFolders(subdir.FullName));
}
// lblFolderSearching.Content = folder.ToString();
}
catch
{
}
return fileArray;
}
我确实添加了 _AddMP3ToListbox = AddMP3ToListbox
它确实将 mp3 添加到列表框中,但它会立即执行此操作,而不是在找到它后立即执行此操作。我该如何解决这个问题?
i'm using Directory.GetFiles
to give me mp3 files, and i'd like to fill a ListBox
with the results, but instead of stopping the program while it goes through the method, can i get it to search and fill the ListBox
up as it gets the mp3 files?
so what i'm using is as follows (and it is failing to add them one at at time, it is adding them all at once when it is done)
private List<string> Getmp3sFromFolders(string folder)
{
List<string> fileArray = new List<string>();
try
{
DirectoryInfo dir = new DirectoryInfo(folder);
var files = dir.EnumerateFiles("*.mp3");
foreach (var file in files)
{
fileArray.Add(file.FullName);
Dispatcher.BeginInvoke(_AddMP3ToListbox, file.Name);
}
var directories = dir.EnumerateDirectories();
foreach (var subdir in directories)
{
fileArray.AddRange(Getmp3sFromFolders(subdir.FullName));
}
// lblFolderSearching.Content = folder.ToString();
}
catch
{
}
return fileArray;
}
i did add _AddMP3ToListbox = AddMP3ToListbox
it does indeed add the mp3's to the listbox, but it does so all at once, not as soon as it finds it. how can i fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
Directory.EnumerateFiles
而不是目录.GetFiles
。EnumerateFiles
将返回系统找到的文件 - 而不是等待所有文件都被找到。在后台线程上执行此操作,并在 UI 线程中使用
Dispatcher.Invoke
或Dispatcher.BeginInvoke
,当发现每个线程时将其添加到ListBox
>。这是我整理的一个简单示例。这是 XAML:
这是隐藏代码:
我绝不打算将其作为最佳实践或包罗万象的示例。只是向您展示一种方法。顺便说一下,我选择了 system32 目录,因为它里面有很多文件,所以我可以测试它。不过,在我的机器上几乎可以立即运行。
Use
Directory.EnumerateFiles
instead ofDirectory.GetFiles
.EnumerateFiles
will return the files as they're found by the system - not wait for all of them to be found.Do this on a background thread and use
Dispatcher.Invoke
orDispatcher.BeginInvoke
to the UI thread as each one is found to add it to theListBox
.Here's a quick example I threw together. Here's the XAML:
and here's the code-behind:
by no means do I intend for this to be a best-practices or all-encompassing example. Just showing you one way to do it. By the way, I picked the system32 directory just because it has a lot of files in it so I could test it. Still works almost instantly on my machine though.