CathalMF
CathalMF

Reputation: 10055

CsvHelper not parsing empty column for double

I'm using CsvHelper to parse my CSV files. In my CSV i have a column which contains a double value, but the csv generation tool can create this as an empty field.

Example CSV

Name,Value,Date
Jim;1.23;20200901
John;;20200901

The Value field for Jim works fine, but when it reaches John with an empty value i get the below exception.

The conversion cannot be performed.
    Text: ''
    MemberType: System.Double
    TypeConverter: 'CsvHelper.TypeConversion.DoubleConverter'
An unexpected error occurred.

I cant find anything in the documentation. I want empty fields to default to 0.

My Code:

public class Transaction
{
    public string Name { get; set; }
    public double Value { get; set; }
    public DateTime Date { get; set; }
}

In this case im running the below like var result = ParseCsvZipArchiveEntry<Transaction>(zipArchiveEntry);

private List<T> ParseCsvZipArchiveEntry<T>(ZipArchiveEntry zipArchiveEntry) where T : class
{
    string TempFilePath = Path.GetTempFileName();

    List<T> Result = null;

    try
    {
        zipArchiveEntry.ExtractToFile(TempFilePath, true);

        CsvHelper.Configuration.CsvConfiguration Config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
        Config.Delimiter = ";";

        using (var reader = new StreamReader(TempFilePath))
        using (var csv = new CsvReader(reader, Config))
        {
            Result = csv.GetRecords<T>().ToList();
        }
    }
    catch (Exception ex)
    {
        Logger(ex.Message);
    }
    finally
    {
        if(File.Exists(TempFilePath))
            File.Delete(TempFilePath);
    }

    return Result;
}

Upvotes: 1

Views: 1846

Answers (1)

rene
rene

Reputation: 42453

You can apply the Default attribute to the property in your model. It is advertised as The default value that will be used when reading when the CSV field is empty.

using CsvHelper.Configuration.Attributes;

public class Transaction
{
    public string Name { get; set; }
    [Default(0)]  // set to 0 when the field is empty
    public double Value { get; set; }
    public DateTime Date { get; set; }
}

In my testing this returns the List of 2 Transaction instances where the second instance has a Value of 0.

enter image description here

The API documentation for that attribute is found here.

Upvotes: 1

Related Questions