Search code examples
c#streambackgroundworker

Read line from text file skipping read lines


I am reading from a text file line by line.

StreamReader reader = new StreamReader(OpenFileDialog.OpenFile()); 

// Now I am passing this stream to backgroundworker
backgroundWorker1.DoWork += ((senderr,ee)=>
{
    while ((reader.ReadLine()) != null)
    {
        string proxy = reader.ReadLine().Split(':').GetValue(0).ToString();
        // here I am performing lengthy algo on each proxy (Takes 10 sec,s) 
    }
});
backgroundWorker1.RunWorkerAsync();

Now problem is that some lines are not being read. It skips each line after one line read.

I have read the total number of lines using

File.ReadAllLines(file.FileName).Length

It gives accurate number of lines.

I suspect there is some problem with BackgroundWorker mechanism in my code, but can't figure it out.


Solution

  • In while ((reader.ReadLine()) != null) you are not assigning the result to anything, as such it (the line which gets read during that call) will get skipped.

    Try some variation of:

    string line = reader.ReadLine();
    while (line != null)
    {
      /* Lengthy algorithm */
      line = reader.ReadLine();
    }
    

    You might prefer:

    string line;
    while ((line = r.ReadLine()) != null) {}