Reading only headers from csv

7.4k Views Asked by At

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??

4

There are 4 best solutions below

2
On BEST ANSWER

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.

2
On

I did not try to use this library. But quick overview of documentation brought this possible solution:

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 documentation and search for header.

0
On

All of the methods in the other answers seem to have been removed in the latest version? This is what worked for me:

using (var fileReader = File.OpenText("data.csv"))
{
    var csv = new CsvReader(fileReader);
    csv.Configuration.HasHeaderRecord = true;
    csv.Read();
    csv.ReadHeader();
    string[] headers = ((CsvFieldReader)((CsvParser)csv.Parser).FieldReader).Context.HeaderRecord;
}
0
On

You can try this instead:

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;
    }