如何使用CsvHelper从特定行读取标头? [英] How to read a header from a specific line with CsvHelper?

查看:390
本文介绍了如何使用CsvHelper从特定行读取标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取CSV文件,其中标头位于第3行:

I'm trying to read a CSV file where header is at row 3:

some crap line
some empty line
COL1,COL2,COl3,...
val1,val2,val3
val1,val2,val3

如何告诉 CSVHelper 标题不在第一行?

How do I tell CSVHelper the header is not at the first row?

我试图用Read()跳过2行,但随后对ReadHeader()的调用引发了一个例外,即标头已被读取.

I tried to skip 2 lines with Read() but the succeeding call to ReadHeader() throws an exception that the header has already been read.

using (var csv = new CsvReader(new StreamReader(stream), csvConfiguration)) {
   csv.Read();
   csv.Read();
   csv.ReadHeader();
   .....

如果我将csvConfiguration.HasHeaderRecord设置为false ReadHeader()再次失败.

If I set csvConfiguration.HasHeaderRecord to false ReadHeader() fails again.

推荐答案

尝试一下:

using (var reader = new StreamReader(stream)) {
      reader.ReadLine();
      reader.ReadLine();
      using (var csv = new CsvReader(reader)) {                    
          csv.ReadHeader();                    
    }
}

这篇关于如何使用CsvHelper从特定行读取标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆