PiotrRybka82
8/21/2016 - 12:23 PM

Read CSV to class object

Pobranie danych z pliku .csv jako lista obiektów danego typu i z wykorzystaniem biblioteki CsvHelper, mapowania, konwerterów

using CsvHelper.Configuration

sealed class MyConverter : CsvHelper.TypeConversion.ITypeConverter
{
  public bool CanConvertFrom(Type type)
  {
    return type == typeof(string);
  }
  
  public bool CanConvertTo(Type type)
  {
    return type == typeof(double);
  }
  
  public object ConvertFromString(CsvHelper.TypeConversion.TypeConverterOptions options, string text)
  {
    var separator = System.Globalization.NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator; 
    text = text.Replace('.', separator[0]);
    return Double.Parse(text);
  }
  
  public string ConvertToString(CsvHelper.TypeConversion.TypeConverterOptions options, object value)
  {
    retur value.ToString();
  }
}
using System.IO;
using CsvHelper;

public static List<myClass> GetRecords<myClass>(
  string path, 
  Type myClassMap, 
  string delimiter = ";")
  {
    var res = new List<myClass>();
    
    using (TextReader reader = File.OpenText(path))
    {
      var csv = new CsvReader(reader);
      
      csv.Configuration.Delimiter = delimiter; 
      
      csv. Configuration.RegisterClassMap(myClassMap);
      
      foreach(myClass i in csv.GetRecords<myClass>())
      {
        res.Add(i);
      }
    }
    
    return res;
  }
using System;
using CsvHelper.Configuration;

class MyClass {}

sealed class MyClassMap : CsvclassMap<MyClass>
{
  MyClassMap()
  {
    Map(m => m.Prop1).Name("Prop1");
    Map(m => m.Prop2).Name("Prop2");
    Map(m => m.Prop3).Name("Prop3").TypeConverter(new MyConverter());
  }
}