从文本文件中读取行并跳过读取行
我正在逐行读取文本文件。
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机制存在一些问题,但无法弄清楚。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 while ((reader.ReadLine()) != null) 中,您没有将结果分配给任何内容,因此它(在该调用期间读取的行)将被跳过。
尝试一些变化:
您可能更喜欢:
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:
You might prefer:
看起来您没有将该行分配给 readline() 调用中的变量。您正在阅读冗长算法中的下一行吗?
根据您的更新,这绝对是您的问题。
你有这个:
你应该有这个:
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:
You should instead have this:
在 while 循环中 reader.ReadLine() 读取一行,并在下一次 string proxy = reader.ReadLine().Split(':').GetValue(0).ToString(); 中读取一行reader.ReadLine() 读取下一行。您尚未将 while 循环中的读取行分配给任何变量。必须对while循环中读取的字符串(Line)进行分割操作。
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.
为什么不使用 File.ReadLines(pathToFile); ?
http://msdn.microsoft.com/en-us/library/dd383503.aspx
Why don't you use File.ReadLines(pathToFile); ?
http://msdn.microsoft.com/en-us/library/dd383503.aspx