使用CsvHelper获取列名列表的最佳方法是什么? [英] What is the best way to get the list of column names using CsvHelper?
本文介绍了使用CsvHelper获取列名列表的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将CsvHelper用于一个项目.我浏览了文档,但是找不到用一种方法读取所有列名的方法.如何使用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);
}
}
}
推荐答案
标头记录在csv上下文中.在访问之前需要先阅读它.
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;
这篇关于使用CsvHelper获取列名列表的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文