Search code examples
c#csvcsvhelper

Getting length of records in CsvHelper


I'm using the CsvHelper library in C# to read a CSV file like this:

var dataCsvFileReader = File.OpenText(inputFile);
var dataCsvReader = new CsvReader(dataCsvFileReader);
var dataRecords = dataCsvReader.GetRecords<dynamic>();

foreach(dynamic record in dataRecords){
    for(int i = 0; i < ???; i++){ //How many columns are there in the record???
        Console.WriteLine($"Record {i} value is: {record[i]}");
    }
}

As you can see from the code, my problem is that I don't know how many columns there are in the record. Since I don't know the structure of the data before parsing it (the CSV files I have as input are always different), how can I find out how many columns there are? I tried to query dataCsvReader.Context.ColumnCount but that always returns 0.


Solution

  • You can convert each record to List

    using (TextReader dataCsvFileReader = File.OpenText(inputFile))
    {
        using (CsvReader dataCsvReader = new CsvReader(dataCsvFileReader))
        {
            while (dataCsvReader.Read())
            {
                var dataRecord = Enumerable.ToList(dataCsvReader.GetRecord<dynamic>());
            }
        }
    }