Search code examples
c#csvhelper

CSVHelper mandatory fields


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?


Solution

  • 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");
            });
        }
    }