Why are files that return the same file more than once listed?

I have this code (thanks to those that have helped so far)

It searches through the directory and all subdirectories, looking for file names.

Files.Clear(); //BindingList<FileInfo> Datasource for a datagridview

Task.Factory.StartNew( () =>
    {
       DirectoryInfo dir = new DirectoryInfo(MainFolder);

       foreach(var file in dir.EnumerateFiles("*" + textBox1.Text + "*.doc?", SearchOption.AllDirectories).Take(200))
       {
          this.BeginInvoke( new Action(() =>
             {
                Files.Add(file);
             }));
       }
     });

The problem is that I install textBox1.textin what I know, only 1 of them, it adds it Files4 times. I tried a break, pointing to this, to be sure that this is not the way I showed it.

I compared 4 objects with each other, they are identical. When I open the search criteria a bit and get 5 results, some of them are 1, some of them double a few triples. therefore there are 5 unique results, but their total number is 10-12.

What am I doing wrong?

+1
source share
3 answers

Invoke.

, . , .

+1

,

Files.Clear();//BindingList Datasource datagridview

    Task.Factory.StartNew( () =>
    {
        DirectoryInfo dir = new DirectoryInfo(MainFolder);
        foreach(var file in dir.EnumerateFiles("*"+textBox1.Text+"*.doc?",SearchOption.AllDirectories).Take(200))
        {
            var currentFile = file;
            this.BeginInvoke( new Action(() =>
            {
                Files.Add(currentFile);
            }));
        }
    });
0

This should work faster and have better clarity.

var searchPattern = "*" + textBox1.Text + "*.doc?";
Files.Clear(); //BindingList<FileInfo> Datasource for a datagridview
DirectoryInfo dir = new DirectoryInfo(MainFolder);
Files.AddRange(dir.EnumerateFiles(searchPatten, SearchOption.AllDirectories).ToList());

Why did you initially use all asynchronous operations?

0
source

All Articles