Vanny
Vanny

Reputation: 23

Streamreader.readLine reads lines through one

I need to read text from txt-file in array. I do it like this

string[] rows = new string[1500000];
        StreamReader file = new StreamReader(adress);
        int count = 0;
        while (file.ReadLine() != null)
        {
            rows[count] = file.ReadLine();
            count++;
        }
        file.Close();

But in target array are only a half of lines.It is the result of working this code. And this is source file. StreamReader read file through one line/ so I lost a half of data. How can i avoid this?

Upvotes: 1

Views: 799

Answers (2)

Azar Shaikh
Azar Shaikh

Reputation: 449

You can use File.ReadAllLines Which reads all text to array

string[] rows = File.ReadAllLines(path);

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Even-numbered rows appear skipped because each iteration of the loop calls ReadLine twice:

  • The first call is in the header of the loop
  • The second call is in the body, on the assignment line

You can fix this by assigning the result of the call to a variable inside the header:

string lastLine;
while ((lastLine = file.ReadLine()) != null)
{
    rows[count] = lastLine;
    count++;
}

Upvotes: 1

Related Questions