S4pehr February 2016

StreamReader output

In C# why output of this 2 code is different from each other ?

StreamReader test = new StreamReader(@"C:\a.txt");

while (test.ReadLine() != null)
{
    Console.WriteLine(test.ReadLine());
}

And this code :

StreamReader test = new StreamReader(@"C:\a.txt");

string line = "";

while ((line = test.ReadLine()) != null)
{
    Console.WriteLine(line);
} 

Answers


Qwertiy February 2016

Each time you call test.ReadLine() you read one new line, so the first code skippes a half of them.


Tomas Nilsson February 2016

In your first example, use this code instead:

while(!test.EndOfStream)
{
   Console.WriteLine(test.ReadLine());
}


Vivek Munshi February 2016

Both the code works same with little magic ,becuase of the reason:

test.ReadLine(): return: The next line from the input stream, or null if the end of the input stream is reached.

      // So,Let's say your a.txt contain the following cases:
       case 1:"Hello World"
       while (test.ReadLine() != null)
        {
            Console.WriteLine("HI" + test.ReadLine());
        }

   // since,we have only one line ,so next line is null and finally it reached the EOD.

    case 2:"Hello World"
   "I am a coder"
       while (test.ReadLine() != null)
        {
            Console.WriteLine("HI" + test.ReadLine());
        }

  // since,we have  two line so ,next line is "I am a coder".
 //It returns:Hi I am a coder.


// And in the below code we are reading and assigning to string variable

        StreamReader test1 = new StreamReader(@"D:\a.txt");

        string line = "";

        while ((line = test1.ReadLine()) != null)
        {
            Console.WriteLine(line);
        } 

Post Status

Asked in February 2016
Viewed 3,407 times
Voted 8
Answered 3 times

Search




Leave an answer