CsvReader错误:找不到索引0处的['ID']名称的标头

时间:2018-02-08 19:42:24

标签: c# csv

我正在尝试使用CsvReader 6.1.1读取一个简单的CSV文件,但一直收到此错误:

找不到索引0处的标题匹配['ID']名称。

这是CSV文件:

"ID","FirstName","LastName","JobTitle","Department","Email"
"1","Necole","Moore","Program Manager ","Housing & Supportive Services","MooreN@AFHouston.org"

这是我正在使用的C#代码:

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

这是CRIContactModel类:

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

我很欣赏有关问题的任何想法。

1 个答案:

答案 0 :(得分:2)

在我的情况下,出现此错误,因为我在csv文件中使用了与CsvHelper预期的不同的分隔符。更改配置后,将按预期csv.Configuration.Delimiter = ";";正常工作。

完整示例:

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