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);
}
}
}
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With