Zain Ali
Zain Ali

Reputation: 15993

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.

Upvotes: 3

Views: 3508

Answers (4)

juFo
juFo

Reputation: 18587

Why don't you use File.ReadLines(pathToFile); ?

http://msdn.microsoft.com/en-us/library/dd383503.aspx

Upvotes: 0

Jason Down
Jason Down

Reputation: 22191

It doesn't look like you're assigning the line to a variable in your readline() call. Are you reading the next line in the lengthy algorithm?

Based on your update, this is definitely your problem.

You have this:

...
while ((reader.ReadLine()) != null)
{
     string proxy = reader.ReadLine().Split(':').GetValue(0).ToString();
     ...
});

You should instead have this:

...
string line;   
while ((line = reader.ReadLine()) != null)
{
    string proxy = line.Split(':').GetValue(0).ToString();
    ...
});

Upvotes: 5

himanshu
himanshu

Reputation: 415

In while loop reader.ReadLine() reads a line and in the next time in string proxy = reader.ReadLine().Split(':').GetValue(0).ToString(); reader.ReadLine() reads next line. You have not assigned the read line in while loop to any variable. You must perform split operation to the string(Line) read in while loop.

Upvotes: 1

Kevin Stricker
Kevin Stricker

Reputation: 17388

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) {}

Upvotes: 10

Related Questions