2

I have data in a file in following format.

HEADER|ReportItem Name: Margin Ri.....
Account Id/Margin Id|Account Name|Ba...... // the row with headers
Data row 1
Data row 2
TRAILER|Record Count: 2

This is throwing an error - I believe due to fact there is a that row before the actual reader row.

using (var textReader = File.OpenText(path))
{
    var csv = new CsvReader(textReader);
    csv.Configuration.RegisterClassMap<GsClassMap>();
    csv.Configuration.TrimOptions = TrimOptions.Trim;
    csv.Configuration.MissingFieldFound = null;
    csv.Configuration.Delimiter = "|";
    csv.Configuration.HasHeaderRecord = true;
    csv.Configuration.ShouldSkipRecord = (x) => x[0].StartsWith("HEADER");
    csv.Configuration.ShouldSkipRecord = (x) => x[0].StartsWith("TRAILER");
    return csv.GetRecords<GsSma>().ToList();
}

This is throwing an error - I believe due to fact there is a that row before the actual reader row.

Header matching ['Account Id/Margin Id'] names at index 0 was not found.

How can I set this up to read the file correctly?

Anand
  • 1,081
  • 1
  • 22
  • 38

1 Answers1

7

When setting ShouldSkipRecord the second time, you're overwriting the first instance. You just need to do this instead.

csv.Configuration.ShouldSkipRecord = row => row[0].StartsWith("HEADER") || row[0].StartsWith("TRAILER");
Josh Close
  • 21,749
  • 11
  • 90
  • 137