Read only csv headers

I am trying to read only the headers from the csv file using CSVHELPER , but I cannot get the GetFieldHeaders() method.

I took the code from this link: Source

  public static String[] GetHeaders(string filePath) { using (CsvReader csv = new CsvReader(new StreamReader("data.csv"))) { int fieldCount = csv.FieldCount; string[] headers = csv.GetFieldHeaders();//Error:doesnt contains definition } } 

But GetFieldHeaders does not work.

Note I only want to read the headers from the csv file.

Refresh . The headers in my csv files look like this:

 Id,Address,Name,Rank,Degree,Fahrenheit,Celcius,Location,Type,Stats 

So can someone tell me what I am missing?

+2
source share
3 answers

Please try under the code ... hope this helps you.

 var csv = new CsvReader(new StreamReader("YOUR FILE PATH")); csv.ReadHeader(); var headers = csv.Parser.RawRecord; 

Note: headers will return all headers together. You will need to make substring (s) for each comma to get each header separately.

+3
source

I have not tried to use this library. But a quick review of the documentation led to this decision:

 public static String[] GetHeaders(string filePath) { using (CsvReader csv = new CsvReader(new StreamReader("data.csv"))) { csv.Configuration.HasHeaderRecord = true; int fieldCount = csv.FieldCount; string[] headers = csv.GetFieldHeaders(); } } 

* See the documentation and find the header .

+2
source

Instead, you can try:

 public IEnumerable<string> ReadHeaders(string path) { using (var reader = new StreamReader(path)) { var csv = new CsvReader(reader); if (csv.Read()) return csv.FieldHeaders; } return null; } 
+1
source

Source: https://habr.com/ru/post/1206478/


All Articles