Search code examples
c#csvhelper

Reading only headers from csv


I am trying to read only headers from a csv file using CSVHELPER but i am unable to get GetFieldHeaders() method of csvhelper.

I have taken 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 is not working.

Note: I only want to read headers from csv file

Update : Headers in my csv files are like below :

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

So can anybody tell me what i am missing??


Solution

  • Please try below code ... hope this will help 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.