Search code examples
c#csvhelper

How to check if header is exists or not in CSV file using CSVhelper


Recently I have migrated my CSVLibrary from 2.7.1 to 30 version. With my old code, if the header is not there, It will not go into the IF condition so that hasHeaderRecord will be false. If the CSV file has a header, then it checks for header count. But after upgrading if the CSV file did not have a header, it goes into the if condition which is not expected.

if (csvReader.Read())
    {
         var csvHeaders = csvReader.HeaderRecord;
         hasHeaderRecord = csvHeaders.Intersect(_Column).Count() == csvHeaders.Count();
    }

How to modify the piece of code after upgration.


Solution

  • I believe your 2.7.1 code did go into the if statement even if there was no header. Your code csvHeaders.Intersect(_ColumnNames).Count() == csvHeaders.Count() is what you used to determine if there was a header. The difference to version 30.0.1 is you have to manually read the header now.

    Version 2.7.1 - Reads line and if no header, automatically tries to assign line to the header

    csvReader.Read()
    

    Version 30.0.1 - Reading the line and assigning the header has been split up. Read(), reads in the line. ReadHeader(), attempts to assign the read line to the header.

    csvReader.Read()
    csvReader.ReadHeader();
    

    Possible upgrade of your code.

    void Main()
    {
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            BadDataFound = null
        };
        
        var _ColumnNames = new string[] {"Id","Name"};
        var hasHeaderRecord = false;
    
        using (var reader = new StringReader("1,name1\n2,name2"))
        using (var csvReader = new CsvReader(reader, config))
        {
            if (csvReader.Read())
            {
                csvReader.ReadHeader();
                
                var csvHeaders = csvReader.HeaderRecord;            
                
                hasHeaderRecord = csvHeaders.Intersect(_ColumnNames).Count() == csvHeaders.Count();
                
            }
        }
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }