从文本文件中读取跳过读取行的行

Zai*_*Ali 3 c# stream backgroundworker

我正在逐行读取文本文件.

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();
Run Code Online (Sandbox Code Playgroud)

现在问题是有些行没有被读取.它在读取一行后跳过每一行.

我已经阅读了使用的总行数

File.ReadAllLines(file.FileName).Length
Run Code Online (Sandbox Code Playgroud)

它给出了准确的行数.

我怀疑我的代码中的BackgroundWorker机制存在一些问题,但无法弄明白.

Kev*_*ker 10

while ((reader.ReadLine()) != null)你没有将结果分配给任何东西,因此它(在该调用期间被读取的行)将被跳过.

尝试一些变化:

string line = reader.ReadLine();
while (line != null)
{
  /* Lengthy algorithm */
  line = reader.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

您可能更喜欢:

string line;
while ((line = r.ReadLine()) != null) {}
Run Code Online (Sandbox Code Playgroud)


Jas*_*own 5

看起来你没有在readline()调用中将行分配给变量.你在阅读冗长算法的下一行吗?

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

你有这个:

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

你应该这样做:

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