Search code examples
c#csvparsingcsvhelper

What is the best way to get the list of column names using CsvHelper?


I am trying to use CsvHelper for a project. I went through the documentation but I couldn't find a way to read all the column names with a single method. How can I get a list of all column header names easily with CsvHelper? I am doing it like this currently but I assume there is a better way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
using System.IO;

namespace Kg
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var reader = new StreamReader(@"myfile.csv"))
            {
                var csv = new CsvReader(reader);

                csv.Read();                  
                var has_header = true;
                var csv_headers = new List<string>();
                var header_index = 0;
                while (has_header)
                {
                    has_header = csv.TryGetField<string>(header_index, out string header_name);

                    if (has_header)
                    {
                        header_index += 1;
                        csv_headers.Add(header_name);

                    }

                }

                Console.WriteLine(csv_headers.Count);

            }
        }
}

Solution

  • The header record is on the csv context. It needs to be read beforehand before accessing.

    csv.Read();
    csv.ReadHeader();
    string[] headerRow = csv.Context.HeaderRecord;