user1269592
user1269592

Reputation: 701

Add files to my ListView using

I want to add the option to my application to add a directory with all the files in the directory into my ListView and because I'm checking each file before add to my ListView (my files are Wiresahrk files so I'm checking the file extension and if the are not pcap format I convert the file and then add) and I want to do it with separate Threads so I'm using BackgroundWorker and I need some help of how to do it:

private void btnAddDir_Click(object sender, EventArgs e)
{
    ListViewItem lv = new ListViewItem();
    string fileToAdd = string.Empty;
    List<string> filesList = new List<string>();
    BackgroundWorker backgroundWorker = null;
    DialogResult dialog = folderBrowserDialog1.ShowDialog();
    if (dialog == DialogResult.OK)
    {
        Editcap editcap = new Editcap();

        foreach (string file in SafeFileEnumerator.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories))
        {
            if (editcap.isWiresharkFormat(file))
            {
                filesList.Add(file);
            }
        }

        backgroundWorker = new BackgroundWorker();
        backgroundWorker.WorkerReportsProgress = true;
        backgroundWorker.DoWork +=
            (s1, e1) =>
            {
                foreach (string fileName in filesList)
                {
                    if (editcap.isWiresharkFormat(fileName))
                    {
                        if (editcap.isLibpcapFormat(fileName))
                        {
                            lv.Text = fileName;
                            lv.SubItems.Add(fileName);
                            lv.SubItems.Add("Waiting");

                            this.Invoke((MethodInvoker)delegate
                            {
                                lvFiles.Items.Add(lv);
                            });

                            lvFiles.Refresh();
                        }
                    }
                }
            };

        backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        (s1, e1) =>
        {

        });

        backgroundWorker.RunWorkerAsync();
    }
}

Upvotes: 0

Views: 240

Answers (1)

Tilak
Tilak

Reputation: 30698

Instead of adding items in backgroundWorker.ProgressChanged event, do it in DoWork.

Otherwise you will get error Cross-thread operation not valid: Control ___ accessed from a thread other than the thread it was created on.

Change

backgroundWorker.ReportProgress(0, fileToAdd);

To

lv.SubItems.Add(fileToAdd);

Also, You donot need to handle ProgressChanged and RunWorkerCompleted event.

Upvotes: 1

Related Questions