Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSVHelper mandatory fields

Tags:

c#

csvhelper

When parsing a csv file, how do i define that a specific field is mandatory. Essentially, I want to make sure that a given field is never empty, and if it is then I would like an exception thrown. Here is the mapping class:

public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).Name("ThirdField"); // this field should be mandatory
    }
}

and the usage:

List<DataType> data;
using (var sr = new StreamReader(localFilePath))
{
    var reader = new CsvReader(sr);
    reader.Configuration.RegisterClassMap<DataMapper>();
    data = reader.GetRecords<DataType>().ToList();
}

Currently I am just checking the results in the data list as follows:

var numberOfInvalidRecords = data.Count(data => string.IsNullOrEmpty(data.Field3));
if (nullAccountHolderRecords > 0)
{
    //handle
}

I was unable to find a built-in feature in the CSVHelper documentation. Am I missing something?

like image 259
doug144 Avatar asked Nov 03 '14 11:11

doug144


4 Answers

I'd probably do this using the ConvertUsing extension:

public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).ConvertUsing(row =>
        {
            if(string.IsNullOrEmpty(row.GetField<string>("ThirdField")))
                throw new Exception("Oops, ThirdField is empty!");
            return row.GetField<string>("ThirdField");
        });
    }
}
like image 118
DavidG Avatar answered Oct 31 '22 06:10

DavidG


Here is a solution that extends the API:

public static class CsvHelperExtensions
{
    public static CsvPropertyMap Required<T>(this CsvPropertyMap map, string columnName)
    {
        return map.Name(columnName).ConvertUsing(row =>
        {
            if (string.IsNullOrEmpty(row.GetField(columnName)))
                throw new CsvParserException($"{columnName} is required, but missing from row {row.Row}");
            return row.GetField<T>(columnName);
        });
    }
}

Usage:

public CsvPersonMap()
{
    Map(m => m.FirstName).Required<string>("First");
    Map(m => m.LastName).Name("Last");
    Map(m => m.MiddleName).Required<string>("Middle");
}
like image 5
Josh Avatar answered Oct 31 '22 08:10

Josh


The developer has now added a Validate method: https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/validation

Using this to validate against a non-null or empty string:

Map(m => m.Id).Validate(field => !string.IsNullOrEmpty(field));

https://github.com/JoshClose/CsvHelper/issues/556

like image 3
Benny Seems Avatar answered Oct 31 '22 06:10

Benny Seems


As suggested by the creator of CsvHelper here:

For the time being, I think you'll have to have WillThrowOnMissingField = false and run a loop and check your specific required fields. You can probably just check the header after the first read.

His sample code:

csv.WillThrowOnMissingField = false;
var list = new List<MyObject>();
var headerChecked = false;
while( csv.Read() )
{
    if( !headerChecked )
    {
        // check for specific headers
        if( !csv.FieldHeaders.Exists( "MyHeaderName" ) )
        {
            throw new Exception( "message" );
        }
        headerChecked = true;
    }

    list.Add( csv.GetRecord<MyObject>() );
}
like image 2
BCdotWEB Avatar answered Oct 31 '22 06:10

BCdotWEB