What is the best way to get the list of column names using CsvHelper?
Solution 1
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;
Solution 2
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;
B A
I am a wannabe programmer and love Ruby. I also write some Javascript. I am learning both Ruby and Javascript and hope to be a better Ruby Programmer someday. Other than these, I am really interested in F# programming language.
Updated on June 10, 2022Comments
-
B A almost 2 years
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); } } }