Reading from text files

Hi,

I have a small question that is bugging me in relation to reading from a file. I created a text file with the numbers 1 to 4, each on a seprate line, and what I am trying to do is read each line one ata time and print them to the screen. Below is my code but the problem is that it is printing out 2 and 4 only, it seems to be skipping 1 and 3

TextReader tr = new StreamReader("Test.txt");

while (tr.readline() != null)

{

Response.Write(tr.ReadLine());

}

tr.Close();

Can anybody shed ant light on it



Answer this question

Reading from text files

  • Ewino

    Hi!

    You have 2 ReadLine() calls, each read a line. You code must looks like this:

    using (TextReader reader = new StreamReader("Test.txt"))

    {

    string str;

    while ((str = reader.ReadLine()) != null)

    {

    Response.Write(str);

    }

    }

    using keyword ensure that Close() will be called even if exception happens. In while loop you read text line into str variable and check that it is not null (null will mean end of stream).



  • Reading from text files