Unable to resolve "CsvHelper.HeaderValidationException : Header with name 'field'[0] was not found"
I have been looking into different issues reporting this same error here in the issues section, but I cannot seem to find the solution. I created my CsvConfiguration adding all things I need, thinking using this may resolve the issue, but looks like is not the case. I have the latest version of CsvHelper installed (27.2.1).
I need to read a csv file with headers which has 1k rows. I have setup my method to read the csv file and return it as a List<>, but as soon as .NET is executing line 'var records = csv.GetRecords<Contact>().ToList();', it returns error "CsvHelper.HeaderValidationException : Header with name 'field'[0] was not found".
` public static List<ContactInfo> getListFromCsvFile(string location) { using (var reader = new StreamReader(location, Encoding.UTF8)) { reader.BaseStream.Position = 0;
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = "\t", BadDataFound = null, HasHeaderRecord = true, TrimOptions = TrimOptions.Trim, MissingFieldFound = null,
IgnoreBlankLines = true
};
using (var csv = new CsvReader(reader, config))
{
csv.Context.TypeConverterOptionsCache.GetOptions<DateTime?>().NullValues.Add("null");
csv.Context.TypeConverterOptionsCache.GetOptions<bool?>().NullValues.Add("false");
csv.Context.TypeConverterOptionsCache.GetOptions<short?>().NullValues.Add("0");
csv.Context.TypeConverterOptionsCache.GetOptions<decimal?>().NullValues.Add("0");
csv.Context.TypeConverterOptionsCache.GetOptions<int?>().NullValues.Add("0");
csv.Context.RegisterClassMap<Mappers>();
var records = csv.GetRecords<ContactInfo>().ToList();
return records;
}
}
}`
Please let me know if anyone needs any more information.
We'd need to see your CSV file and your class map for ContactInfo to help you with this.
Had the same issue today, here's what helped me - https://github.com/JoshClose/CsvHelper/issues/1348#issuecomment-508525154 https://github.com/JoshClose/CsvHelper/issues/1653#issuecomment-763608811
I too am facing the same issue CsvHelper version 29.0
public static IEnumerable<T> ReadFromCsv<T>(string csv)
{
var conf = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ",",
HasHeaderRecord = true,
TrimOptions = TrimOptions.Trim,
MissingFieldFound = null
};
using (var stringReader = new StringReader(csv))
using (var csvReader = new CsvReader(stringReader, conf))
{
return csvReader.GetRecords<T>().ToList(); // **gives exception Header with name 'FormId'[0] was not found.**
}
}
it is called like this
ReadFromCsv<Form>(csvString).FirstOrDefault()
public class Form
{
public Int64 FormId { get; set; }
public Int64 FormTypeId { get; set; }
}
csvString = "FormId,FormTypeId 22,3"