Search code examples
c#csvhelper

CSVHelper cannot convert empty float values to string


I have a csv file that contains integer, string, bool, and float types of data. The problem is, that some fields are empty. When I try to read the csv file with csvhelper, I get TypeConversion.TypeConverterException error. I checked the details, and looks like it's because it can't convert the empty float values to string. How can I handle it?

namespace Smh
{
    class Program
    {
        static void Main(string[] args)
        {
            List<E> EList = new List<E>();
            List<E2> EList2 = new List<E2>();

            string filePath = @"D:\Visual Studio\Projects\Example\boo.csv";

            using (var reader = new StreamReader(filePath))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                var example= new E();
                EList= csv.GetRecords<E>().ToList();
            }
.
.
.

A part of my "E" class:

.
.
 public float weight { get; set; }
.
.

and the error I get: https://i.postimg.cc/dVPkYDCm/image.png

A short part of the csv file:

id | speed | type | weight
1     40     type1   5.4
2     43     type2
3     16     type3   5.2 

Solution

  • The simplest solution with out using a ClassMap Custom mapper, is to change the type to float?.

    public class Test{
        public int id{get;set;}
        public int speed{get;set;}
        public string type{get;set;}
        public float? weight{get;set;}
    }
    

    Then If you need to change the default value you can add a Getter Setter that will return Single.NaN

    Example: Live Demo

    public static void Main()
    {
        var result = new List<Test>();
        using (var stream = new MemoryStream())
        using (var writer = new StreamWriter(stream))
        using (var reader = new StreamReader(stream))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            //Csv Creation
            writer.WriteLine("id,speed,type,weight");
            writer.WriteLine("1,40,type1,5.4");
            writer.WriteLine("2,43,type2,");
            writer.WriteLine("3,16,type3,5.2");
            writer.Flush();
            stream.Position = 0;
            
            
            csv.Configuration.HasHeaderRecord = true;
            csv.Configuration.Delimiter = ",";
            
            result = csv.GetRecords<Test>().ToList();           
            
        }
        result.Dump();
    }