SearchForKnowledge
SearchForKnowledge

Reputation: 3751

Why doesn't the CSV parser exit the loop?

I have a foreach statement which iterates through a CSV file and displays the fields which are in an array:

foreach (string line in lines)
{
    //MessageBox.Show(line);
    using (TextFieldParser parser = new TextFieldParser(textBox1.Text))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            foreach (string field in fields)
            {
                colArray.Add(field);
            }
            MessageBox.Show(string.Join(",", colArray));
            colArray.Clear();
        }
    }
}

My CSV has 5 rows, so what the above code is doing is displaying the messagebox from the first row to the last row and then goes back to showing the first row to the last row and continues to do it... How do I exit when the last row has been reached on the first iteration?

Upvotes: 0

Views: 236

Answers (2)

quantdev
quantdev

Reputation: 23813

Because of this first line (as I said in my comments) :

foreach (string line in lines)

You will be doing the complete CSV processing (showing every fields of every lines) once per line in your CSV.

You probably want to remove this foreach loop.

EDIT :

You code does exit the while loop, and does exit the surrounding foreach, but only after a lot of useless iterations.

Upvotes: 2

Servy
Servy

Reputation: 203837

Here is your code, in pseudocode form:

for each line in the file
  print out every single line in the file

This, understandably, prints out every line of the file more than once, although not infinitely many times. It will print out every line in the file once for each line in the file.

To just print out every line in the file once, remove the outer foreach.

Upvotes: 2

Related Questions