Ree
Ree

Reputation: 29

My StreamReader code is reading only every other line c#

This is my solved program that will read a text file with delimiters and transfer the data to a table using datagridview.

Now I'm having a hard time because the while loop is only reading every other line.

This is my code:

private void Form1_Load(object sender, EventArgs e)
{

    TextReader tr = new StreamReader("aplusixdata.txt");
    string[] columns = {"School","Room No.","Student No.","Excercise No.","Problem No.",
                                   "Nth Problem Taken","Date","Time","Excercise Degree",
                                   "Action No.","Duration","Action","Error","Etape",
                                   "Expression","Etat","Cursor Location","Selection",
                                   "Equivalence","Resolution","Empty"};

    while (tr.ReadLine() != null)
    {
        int i = 0;                
        char[] delimiterChar = { ';' };
        string words = tr.ReadLine();
        text = words.Split(delimiterChar);
        DataRow row = t.NewRow();
        foreach (String data in text)
        {
            //System.Console.WriteLine(data);
            System.Console.WriteLine(i);
            row[columns[i]] = data;
            i++;
        }
        t.Rows.Add(row);
    }
}

Upvotes: 1

Views: 3282

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503779

You're calling ReadLine twice on every iteration - once here:

while (tr.ReadLine() != null)

and once here:

string words = tr.ReadLine();

Change it to only read once per iteration:

char[] delimiterChar = { ';' };

string words;
while ((words = tr.ReadLine()) != null)
{
    int i = 0;                
    text = words.Split(delimiterChar);
    ...
}

(Note that I've also pulled the creation of the char[] out of the loop - there's really no need to do that on every iteration. I'd personally make it a private static variable.)

A couple of other style points:

  • Where is your text variable declared? Why not declare it in the loop itself?
  • I would elide the declaration and first assignment of row:

    DataRow row = t.NewRow();
    

EDIT: As per shahkalpesh's answer, you really should use a using statement to make sure your reader is closed at the end.

Upvotes: 9

shahkalpesh
shahkalpesh

Reputation: 33484

That is because you are making a call to ReadLine twice.

A better way could be:
while (!tr.EndOfStream)

EDIT: It will be better to have the code surrounded by using clause.

using (TextReader tr = new StreamReader("aplusixdata.txt"))
{
  //.. your code here that reads the file line by line
}

Upvotes: 3

Related Questions