0

我正在尝试创建一个工具来从多个 .txt 文件中搜索数据。我想为用户创建一个进度条来跟踪工作的进度。这就是我得到的

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    String terms;
    StringBuilder sb;
    if (filePath != "")
    {
        sb = new StringBuilder();
        //I use another function to add path to string filePath, 
        //seperated by \r\n
        String[] fpath = filePath.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string path in fpath)
        {
            if (!String.IsNullOrEmpty(path))
            {                     
                lines = File.ReadAllLines(path);
                for (int i = 0; i < lines.Count(); i++)
                {
                    terms = lines[i];
                    if (terms.Contains("Content to look for"))
                    {
                        sb.AppendLine(lines[i]);                                
                    }
                    //Problem here
                    backgroundWorker1.ReportProgress(i);
                }
            }
        }
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value += (progressBar1.Maximum * e.ProgressPercentage / 100);
    lblPercent.Text = e.ProgressPercentage.ToString() + " %";
}

当我添加行时:

backgroundWorker1.ReportProgress(i);

它抛出异常:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

我尝试使用 Ivoke,但它仍然抛出此异常:

Invoke((Action)(() =>
{
    String terms;
    StringBuilder sb;
    if (filePath != "")
    {
        sb = new StringBuilder();
        String[] fpath = filePath.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string path in fpath)
        {
            if (!String.IsNullOrEmpty(path))
            {
                lines = File.ReadAllLines(path);
                for (int i = 0; i < lines.Count(); i++)
                {
                    terms = lines[i];
                    if (terms.Contains("Content to look for"))
                    {
                        sb.AppendLine(lines[i]);
                    }
                    backgroundWorker1.ReportProgress(i);
                }
            }
        }
    }
}));

你能告诉我哪里错了吗?

4

0 回答 0