Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8435899
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T07:02:40+00:00 2026-06-10T07:02:40+00:00

I have this code first the constructor and button click event: using System.Text; using

  • 0

I have this code first the constructor and button click event:

using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
using System.Collections;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DirectoryInfo dirinf = new DirectoryInfo(@"C:\");
        List<FileSystemInfo> fsi = new List<FileSystemInfo>();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
            button1.Enabled = false;
        }

Then i have a search function and a backgroundowrker DoWork event:

public void Search(string strExtension,
                            DirectoryInfo di,
                            List<FileSystemInfo> pResult)
        {
            try
            {

                foreach (FileInfo fi in di.GetFiles())
                {
                    if (InvokeRequired)
                    {
                        BeginInvoke(new Action(() => label2.Text = fi.Name));
                    }
                    if (fi.Name == "MessageLog.xsl")
                    {
                        foreach (FileInfo fii in di.GetFiles())
                        {
                        if (fii.Extension == strExtension)
                            pResult.Add(fii);
                        }
                        if (InvokeRequired)
                        {
                            BeginInvoke(new Action(() => textBox1.AppendText("Number Of History Files Found: ===> " + pResult.Count.ToString() + Environment.NewLine)));
                        }

                    }
                }

                    foreach (DirectoryInfo diChild in di.GetDirectories())
                        Search(strExtension, diChild, pResult);

            }
            catch (Exception e)
            {
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Search(".xml", dirinf, fsi);
            for (int i = 0; i < fsi.Count; i++)
            {
                if (InvokeRequired)
                {
                    BeginInvoke(new Action(() => textBox1.AppendText(fsi[i - 1].FullName + Environment.NewLine)));
                }

            }
        }

When its getting to the part in the DoWork event:

for (int i = 0; i < fsi.Count; i++)
                {
                    if (InvokeRequired)
                    {
                        BeginInvoke(new Action(() => textBox1.AppendText(fsi[i - 1].FullName + Environment.NewLine)));
                    }

                }

After one or two itertions its throwing exception in the Program.cs on the line:

Application.Run(new Form1());

Exception has been thrown by the target of an invocation

Solved it by reporting to the backgroundworker completed event:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Search(".xml", dirinf, fsi);
            backgroundWorker1.ReportProgress(100);

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            for (int i = 0; i < fsi.Count; i++)
            {                
                    textBox1.AppendText(fsi[i].FullName + Environment.NewLine);
            }
        }

Working just good.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T07:02:42+00:00Added an answer on June 10, 2026 at 7:02 am

    You have already solved the issue (correctly, this should be done in the Completed event).

    What remains is an explanation:

    You are using the variable i , that is local to the DoWork method, inside the Action lambda. This means all code uses 1 shared (boxed) version of the variable. It’s called ‘closing over the loop var’.

    The symptoms fit: the lambdas are executed async, when the 2nd or 3rd starts executing the main loop has already made i == fsi.Count. The (inner) exception should be “Index out of range”.

    for (int i = 0; i < fsi.Count; i++)
    {
        if (InvokeRequired)
        {
            BeginInvoke(new Action(() => 
                textBox1.AppendText(fsi[i - 1].FullName   // captured 'i'
                + Environment.NewLine)));
        }
    }
    

    It can be fixed this way:

    for (int i = 0; i < fsi.Count; i++)
    {
        if (InvokeRequired)   
        {
            int iCopy = i;     // 1 instance per loop
    
            BeginInvoke(new Action(() => 
                textBox1.AppendText(fsi[iCopy - 1].FullName  
                + Environment.NewLine)));
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been using this code with great success to pull out the first
I have two forms. First one is to decide numbers of button by using
First, within the Program.Program() static constructor I have this code: AppDomain.CurrentDomain.UnhandledException += (s, eargs)
I have this code: tableList = [[NSMutableArray alloc] initWithObjects:@First View,@Second View,nil]; I have synthesized
I have this code. Only the first drawLine gets drawn and the rest 2
I currently have this code which reads the first field in a database record
I have an Entity in Code First Entity framework that currently looks like this:
I have this view (DetailsContainer, first class in code section of this question) with
The code i current have is this. function update (){ latest_id = $('#image:first').data('position'); /*
my code is like this: i have two classes first class: public class Box<E>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.