使用readline / writeline的奇怪结果

时间:2017-09-19 14:47:28

标签: c# parsing streamreader streamwriter

大家好!天才!

我尝试创建一个读取txt文件的代码,并从该文件中以“PART”一词开头,并将其放入一个新文件中。

不知何故,输出文件在原始文件的每一行中都丢失了。 这是我的代码:

{
    string line ="";
    string Starttext = "PART";
    using (System.IO.StreamReader reader = new System.IO.StreamReader(@"C:\Users\tsnm2171\Desktop\processed\LABB\ORIGINAL.txt"))          
    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\Users\tsnm2171\Desktop\processed\LABB\OUTPUT.txt"))


        while (reader.ReadLine() != null)                   

        {   line = reader.ReadLine();

            if (line.StartsWith(Starttext))
                {
                    //writes/starts a new line beginning with PART

                    writer.WriteLine(line);
                }
                else 

                {
                    //appends info to same line (beginning with a space)
                    writer.Write(" " + line);
                }                       
        }
}        

原始文件如下所示:

KABEL           RXF 4x25
PART        01      1   1       
PART        02      2   2       
PART        03      3   3       
PART        04      4   4       
PART        SH      GND GND     
KABEL           RXF 4x35    0000000456  Cable RXF 4x35
PART        01  1   5   5       
PART        02  1   6   6       
PART        03  1   7   7       
PART        04  1   8   8       
PART        SH  1   GND GND     
KABEL           RXF 4x35    0000000456  Cable RXF 4x35
PART        01  1   9   9       
PART        02  1   10  10      
PART        03  1   11  11      
PART        04  1   12  12      
PART        SH  1   GND GND

但输出文件缺少“Part 02”和“Part 04”行,如下所示:

PART        01      1   1       
PART        03      3   3       
PART        SH      GND GND     
PART        01  1   5   5       
PART        03  1   7   7       
PART        SH  1   GND GND     
PART        01  1   9   9       
PART        03  1   11  11      
PART        SH  1   GND GND

为什么?

1 个答案:

答案 0 :(得分:4)

reader.ReadLine()实际上从文件中读取一行并将光标移动到下一行。

您已在reader.ReadLine()循环

中两次致电while

正确的方法是

while ((line = reader.ReadLine()) != null) 
{
   // Do your work
}