Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CsvHelper getting just the headers row

Tags:

csvhelper

I am trying to read an uploaded CSV file and before doing anything with the data I need to check the first header name to be sure it is the correct file. I have been trying to find a way to do it but the reader skips to the second row instead. Is there a direct way of selecting one of the headers and checking its value?

like image 692
Miko Avatar asked Sep 16 '14 13:09

Miko


2 Answers

You can use the CsvReader to get the header row strings as described in this answer:

using (var csv = new CsvReader(reader))
{
    csv.Read();
    csv.ReadHeader();
    string[] headerRow = csv.Context.HeaderRecord;
}
like image 191
Rick Jolly Avatar answered Oct 19 '22 05:10

Rick Jolly


You can use the parser directly if you want to just check the first row.

var parser = new CsvParser( textReader );
var row = parser.Read();
if( row[0] == "MyColumn" ) { /* do something */ }

If you're using a Stream, you will need to reset it to the beginning if you're going to use it again.

like image 40
Josh Close Avatar answered Oct 19 '22 06:10

Josh Close