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.
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) {}
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();
...
});
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.
Why don't you use File.ReadLines(pathToFile); ?
http://msdn.microsoft.com/en-us/library/dd383503.aspx
精彩评论