CsvHelper: How to ignore the header row?

Viewed 5968

I'm using the CsvHelper package to parse a TSV file.

I wish to process each record a time, without automatically deserializing into a class, as I need to process the fields individually.

However, even if I set HasHeaderRecord = true, I am getting the header returned as the first record in the loop.

The docs say: "Read() Advances the reader to the next record. This will not read headers. You need to call CsvHelper.CsvReader.Read then CsvHelper.CsvReader.ReadHeader for the headers to be read".

And this GitHub issue says: "Calling Read() will read in the current record. If you have a header record, you need to call ReadHeader afterwards".

But this still doesn't make sense to me, in the below code. Should I be calling ReadHeader for every row (within the loop)? That makes no sense, plus I tried and it throws an exception.

For now, I can just manually ignore the first record, but I am curious about the ReadHeader method, and my understanding of the above!

using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
csv.Configuration.Delimiter = "\t";
csv.Configuration.HasHeaderRecord = true;
while (csv.Read())
{
    if (csv.Context.Record.Length != numExpectedColumns)
    {
        errors++;
        continue;
    }

    int i = 0; // Calculate which index to be reading from based on various factors.
    string interestingField = csv[i];
}
0 Answers
Related