Dunnoman
Dunnoman

Reputation: 11

CSV Helper, Ignore empty Values

I'm using CSVHelper to read to types of csv files:

1.

6000000,1,2020
6000001,1,2020
6000002,1,2020
6000003,1,2020
6000004,1,2020
6000000
6000001
6000002

This is my model:

public class Body
    {
        public long Id { get; set; }

        public int Semester { get; set; }

        public int Year { get; set; }
    }

This Model works fine for the first type of file. But in case of second it throws exceptions. I think it is because there are no fields for Semester and Year in CSV. Is there a way to ignore those 2 additional fields while reading that do not exist in 2nd file? I do not want to create additional Model with only Id property.

My method for reading csv:

public List<T> ReadFile<T>(StreamReader stream)
        {
            using (var csv = new CsvReader(stream, CultureInfo.InvariantCulture))
            {
                csv.Configuration.HasHeaderRecord = false;
                var records = csv.GetRecords<T>().ToList();
                return records;
            }
        }

So if i were to read the 2nd file, then there would be returned List with Body objects but Semester and Year properties would be empty or 0

Upvotes: 1

Views: 2310

Answers (1)

Phil Golding
Phil Golding

Reputation: 471

OptionalAttribute: From the CSVHelper docs: 'Ignore the member when reading if no matching field name can be found.'

Just tag your model up like this:

public class Body
    {
        public long Id { get; set; }
        [Optional]
        public int Semester { get; set; }
        [Optional]
        public int Year { get; set; }
    }

Or using a ClassMap:

public class BodyMap : ClassMap<Body>
{
    public BodyMap()
    {
        Map(m => m.Id);
        Map(m => m.Semester).Optional();
        Map(m => m.Year).Optional();
    }
}

Then add the following:

csv.Configuration.RegisterClassMap(new BodyMap());

Upvotes: 4

Related Questions