Home > OS >  How to report progress files names from loop in backgroundworker dowork event to progresschanged eve
How to report progress files names from loop in backgroundworker dowork event to progresschanged eve

Time:11-05

I'm trying to report progress of each found file in the loop when the file is get adding to the FilesFound List report the file name to the progreschanged and in the progresschanged display the file name on a label.

The loop method

private void SearcherCore(string sDir)
        {
            try
            {
                foreach (var directory in Directory.GetDirectories(sDir))
                {
                    foreach (var filename in Directory.GetFiles(directory))
                    {
                        using (var streamReader = new StreamReader(filename))
                        {
                            var contents = streamReader.ReadToEnd().ToLower();

                            if (contents.Contains(SearchText))
                            {
                                FilesFound.Add(filename);
                            }
                        }
                    }

                    SearcherCore(directory);
                }
            }
            catch (System.Exception ex)
            {
                
            }
        }

The dowork event

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (textBoxSearchDirectory.Text != "")
            {
                SearcherCore(textBoxSearchDirectory.Text);
            }
        }

The progresschanged event is still without code.

CodePudding user response:

The BackGroundWorker.ReportProgress method will be useful. you can use the overload that takes an int and object as parameters.

so when you find a file you would do something like:

backgroundWorker1.ReportProgress(0, filename);

(so this would go under your FilesFound.Add(filename); line.

the 0 is the percentProgress which you don't seem to care about in this case.

Then you would implement the backgroundWorker1_ProgressChanged event. To get the file name, you can use the UserState Property of the ProgressChangedEventArgs.

  • Related