Search code examples
c#csvcsvhelper

CSVHelper issue with reading CSV to custom object


I'm trying to read a CSV file into my custom objects, but every time I get an error saying that such fields don't exist. However, they do actually exist.

Here's my code:

public class Order
{
    public string isin { get; set; }
    public double price { get; set; }
}

class OrderMap : CsvClassMap<Order>
{
    [System.Obsolete("use CreateMap", true)]
    public override void CreateMap()
    {
        Map(m => m.isin).Index(0);
        Map(m => m.price).Index(1);
    }
}

static void Main(string[] args)
{
    StreamReader file = new StreamReader(@"data\1\my_file.csv");
    var csv = new CsvReader(file);
    csv.Configuration.RegisterClassMap<OrderMap>();
    var orderFlow = csv.GetRecords<Order>().ToList();

When I try to access certain field via getField<string>(Index) I get the same error for all indexes above 0. getField<string>(0) returns the entire row separated with ;. What's wrong?


Solution

  • The problem is that you have not specified your delimiter as a ;. The default delimiter is ,. You need to update your configuration. You can find additional information on the library site.

    csv.Configuration.Delimiter = ";";