Question

Quick help here please on csvhelper...

csv: Name,LastName

PersonMap:

    public override void CreateMap()
    {
        Map(x => x.Name).Name("Name");
        Map(x => x.LasName).Name("LastName");
    } 

Person Class:

  public string Name { get; set; }
  public string LastName { get; set; }

Main:

 public void writePerson()
 {
        IEnumerable<Person> records;
        using (var r = new CsvReader(new StreamReader("person.csv")))
        {
            r.Configuration.RegisterClassMap<PersonMap>();
            records = r.GetRecords<Person>().ToList();     
        } 

        using (var w = new CsvWriter(new StreamWriter("person.csv")))
        {
            w.Configuration.RegisterClassMap<PersonMap>();
            w.WriteRecord(records); //rewrite csv list
            w.WriteField("John")); 
            w.WriteField("Doe");
            w.NextRecord();             
        }
    }

ERROR LINE: records = reader.GetRecords().ToList();

ERROR: No header record was found.

Was it helpful?

Solution

ok so I fixed it with the following:

Write:

string persondata = "John, Doe";
using (FileStream fs = new FileStream("person.csv", FileMode.Append, FileAccess.Write))
        using (StreamWriter sw = new StreamWriter(fs))
        { sw.WriteLine(persondata); sw.Dispose(); }

Read:

IEnumerable<Person> records;
using (var reader = new CsvReader(new StreamReader(@"person.csv")))
{
        reader.Configuration.RegisterClassMap<PersonMap>();
        records = reader.GetRecords<Person>();
}

OTHER TIPS

Looks like your person.csv doesn't have the first line as a header line as follows:

Name,LastName

Please check the CSV file.

Add following configuration line

w.configuration.HasHeaderRecord = false;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top