Skip to content

CsvReader.GetRecords with ShouldSkipRecord may skip the header row #2368

@ryst

Description

@ryst

Describe the bug
When using CsvConfiguration.ShouldSkipRecord, CsvReader.GetRecords may skip the header row.

To Reproduce

public class CsvData
{
    public string Name { get; set; }
}
var csvContent = "Name\nArnold\nAndrew\nBetty\nFrank";

using var stream = new MemoryStream(Encoding.UTF8.GetBytes(csvContent));
using var reader = new StreamReader(stream);

var configuration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    ShouldSkipRecord = shouldSkipRecordArgs => !shouldSkipRecordArgs.Row[0].StartsWith("A")
};

var csvReader = new CsvReader(reader, configuration);
var records = csvReader.GetRecords<CsvData>().ToList();

Expected behavior
GetRecords should return two records, Arnold and Andrew. However, the header row is skipped and "Arnold" becomes the header. Then a HeaderValidationException is thrown for missing header with name "Name". ShouldSkipRecord should not apply to the header row.

Additional context
If I add a ClassMap to map index 0 to the Name property, I won't get the HeaderValidationException, but the GetRecords will only return one record, Andrew.

class CsvDataMap : ClassMap<CsvData>
{
    public CsvDataMap()
    {
        Map(m => m.Name).Index(0);
    }
}
csvReader.Context.RegisterClassMap<CsvDataMap>();

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions