Directory.GetFiles, how do I get it to spit out objects, how will they find them?

I use Directory.GetFilesto give me mp3 files, and I would like to fill in the ListBoxresults, but instead of stopping the program while it goes through, can I get it to search and fill ListBoxup, since it will receive mp3 files?

so I use the following (and he cannot add them in time, he adds them all at once, when this 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 added _AddMP3ToListbox = AddMP3ToListbox

he really adds mp3 to the list, but he does it right away, and not right away, as soon as he finds it. how can i fix this?

+5
source share
1 answer

Directory.EnumerateFiles Directory.GetFiles. EnumerateFiles , , - , .

Dispatcher.Invoke Dispatcher.BeginInvoke , ListBox.

, . XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <ListBox x:Name="_FileList" />
        <Button Grid.Row="1" Content="Go!" Click="Button_Click" />
    </Grid>
</Window>

-:

using System;
using System.IO;
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Action<string> _AddToListBox;

        public MainWindow()
        {
            InitializeComponent();
            _AddToListBox = AddToListBox;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Action action = Go;
            action.BeginInvoke(null, null);
        }

        private void Go()
        {
            foreach (var file in Directory.EnumerateFiles(@"c:\windows\system32\"))
            {
                Dispatcher.BeginInvoke(_AddToListBox, file);
            }
        }

        private void AddToListBox(string toAdd)
        {
            _FileList.Items.Add(toAdd);
        }
    }
}

. . , system32 , , . , .

+11

All Articles