Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);

            }
        }
}
like image 607
B A Avatar asked Jan 17 '18 18:01

B A


2 Answers

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;
like image 54
Paul Wild Avatar answered Oct 07 '22 18:10

Paul Wild


The previous answer used to work fine, but as of version 20 of csvhelper there is a breaking change. Now just access the header record from the reader directly:

csv.Read();
csv.ReadHeader();
string[] headerRow = csv.HeaderRecord;
like image 6
JumpingJezza Avatar answered Oct 07 '22 16:10

JumpingJezza