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?
Asked
Active
Viewed 1.8k times
19
-
Does this answer your question? [What is the best way to get the list of column names using CsvHelper?](https://stackoverflow.com/questions/48307466/what-is-the-best-way-to-get-the-list-of-column-names-using-csvhelper) – JumpingJezza Feb 16 '21 at 01:38
2 Answers
21
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;
}

Jeankowkow
- 814
- 13
- 33

Rick Jolly
- 2,949
- 2
- 23
- 31
-
Important note on this method is that if you read the HeaderRecord, it seems to push the cursor down a row, which will result in a later call to GetRecords() having 1 fewer rows. To get around this I had to GetRecords().ToList(), then read the csv.HeaderRecord. Everything is fine if you do it like that. Also, if you don't call ToList(), the issue will persist. – Don Rolling Mar 11 '22 at 21:19
9
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.

Josh Close
- 22,935
- 13
- 92
- 140