2011-07-16 203 views
3

我正在逐行读取文本文件。从文本文件中读取线路跳过读取行

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(); 

现在问题是某些行不被读取。它在读取一行后跳过每一行。

我已阅读使用

File.ReadAllLines(file.FileName).Length 

它让行的准确数量的行的总数。

我怀疑我的代码中存在BackgroundWorker机制的问题,但无法弄清楚。

回答

10

while ((reader.ReadLine()) != null)你没有将结果分配到任何东西,因此它(这被在使用读行呼叫)将被跳过。

尝试的一些变化:

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

你可能会喜欢:

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

它看起来并不像是在readline()调用中将行分配给一个变量。你在阅读冗长算法中的下一行吗?

根据您的更新,这绝对是您的问题。

你有这样的:

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

而应该有这样的:

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

我更新的问题 –

+0

是否有可能在同时子句声明串! –

+0

@ Zain:我认为你是对的,你不能。自从我大部分时间使用foreach循环以来,习惯的力量。我使用Jon Skeet的LineReader类,所以它通常看起来像这样:foreach(var line in new LineReader(fileName)){}; –

1

在while循环reader.ReadLine()读取一行,并在串代理接下来的时间= reader.ReadLine ().Split( ':')。的GetValue(0)的ToString(); reader.ReadLine()读取下一行。您尚未将while循环中的读取行分配给任何变量。您必须对while循环中读取的字符串(Line)执行拆分操作。