0

i wanted to get value by text file
the text file has two-columns integer data and they are split by blank such like "82 10"
the file has many rows, at least 100 rows
anyway, the error is occurred when my program is processing in final row !
for example, the final part of text file is
12 15
15 16
20 45
then the console is show
12 15
15 16
and NullReferenceException error is occurred
I know meaning of error, my question is not what is NULLRef error but why it is occured although I already put the condition in while sentences

here is my code

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader file = new StreamReader(@"E:\text.txt");
            int tmpx = 0, tmpy = 0;
            while (file.ReadLine() != null)
            {
                string[] component = file.ReadLine().Split(' ');
                int.TryParse(component[0], out tmpx);
                int.TryParse(component[1], out tmpy);
             //   Console.Write(file.ReadLine()+"\n");
                Console.Write(tmpx + " " + tmpy +"\n");
            }
        }
    }
}
Lucid
  • 21
  • 1
  • 5
  • The most likely reason is that you skip lines, your while-loop reads 1 line, and if **this** line is not null, it enters the loop block, which reads **its own line**. This line may very well be null. The preferred way to do this is to declare a line variable just before the loop: `string line;`, then rewrite your while loop like this: `while ((line = file.ReadLine()) != null)`, and then use the `line` variable inside the loop to refer to the line that was read. – Lasse V. Karlsen Jun 21 '17 at 06:56
  • Remember that each time you call `file.ReadLine()` you read the next line, there is nothing magical here that understands that you really want to refer to the previously read line in your second call. So make sure you only call `file.ReadLine()` once per loop iteration and you should be OK. – Lasse V. Karlsen Jun 21 '17 at 06:57
  • @LasseV.Karlsen Oh god ... thank you very much ... It makes me sad that I can't vote you ... thank you !!! – Lucid Jun 21 '17 at 07:10

0 Answers0