Search code examples
csvcsvhelper

How to ignore separator definition while parsing a file?


I'm using CsvHelper, but my parsing is crashing if the first line of the file is like sep=,

I'm doing it like this:

    using var reader = new StreamReader(fileStream);
    using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

    return csv.GetRecords<ClassToReadInto>()
        .Select(t => new ClassToMapTo
        {
            // map goes here
        })
        .ToList();

What happens is:

    CsvHelper.HeaderValidationException: Header with name 'Type'[0] was not found. // and a bunch of other names

So CsvHelper is just trying to treat the first row as a header row. I doubt it even sets the separator from this row. To work this around I only came up with something like this:

    while (csv.Read())
    {
        csv.ReadHeader();

        try
        {
            csv.ValidateHeader(typeof(CsvOrder));
            break;
        }
        catch { }
    }

Is there "the right way" to do so?


Solution

  • If it's always there, you can just read a row first.

    csv.Read();
    var records = csv.GetRecords<ClassToReadInto>();
    

    If it's not always there, you'll need to do a check.

    csv.Read();
    if (!csv[0].StartsWith("sep="))
    {
        // The first row is the header, so we need to read it.
        csv.ReadHeader();
    }
    var records = csv.GetRecords<ClassToReadInto>();