I'm trying to read a simple CSV file using CsvReader 6.1.1 but keep getting this error:
Header matching ['ID'] names at index 0 was not found.
Here's the CSV file:
"ID","FirstName","LastName","JobTitle","Department","Email"
"1","Necole","Moore","Program Manager ","Housing & Supportive Services","[email protected]"
Here's the C# code I'm using:
Stream stream = await Request.Content.ReadAsStreamAsync();
StreamReader sr = new StreamReader(stream);
var csv = new CsvReader(sr);
var records = csv.GetRecords<CRIContactModel>();
foreach(var record in records) //***Fails here***
{
var contact = _criContactService.FindAsync(x => x.ID == record.ID);
if (contact != null)
{
_criContactService.Update(record, record.ID);
}
else
{
_criContactService.Add(record);
}
}
Here's the CRIContactModel class:
public class CRIContactModel
{
public int ID { get; set; }
[Required]
[StringLength(25)]
public string FirstName { get; set; }
[Required]
[StringLength(25)]
public string LastName { get; set; }
[Required]
[StringLength(50)]
public string JobTitle { get; set; }
[Required]
[StringLength(50)]
public string Department { get; set; }
[Required]
[StringLength(150)]
public string Email { get; set; }
}
I appreciate any ideas on what the issue could be.
In my case I got this error, because i used a different delimiter in my csv files as the CsvHelper expected. After changing the configuration bevore reading everything worked as expected csv.Configuration.Delimiter = ";";.
Full Example:
Stream stream = await Request.Content.ReadAsStreamAsync();
StreamReader sr = new StreamReader(stream);
var csv = new CsvReader(sr);
csv.Configuration.Delimiter = ";";
var records = csv.GetRecords<CRIContactModel>();
foreach(var record in records) {
var contact = _criContactService.FindAsync(x => x.ID == record.ID);
if (contact != null) {
_criContactService.Update(record, record.ID);
}
else {
_criContactService.Add(record);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With