1

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

1
  • 1
    Empty values are ,,,, the separator should be always present. Since you are using library it works correctly. Commented Jul 10, 2020 at 13:13

1 Answer 1

4

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());

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, Thanks, It looks like it works with Optional, but i had to set Semester and Year as string because with int type i was getting exception
I believe you could also use a nullable int public int? Semester
As David Specht said - changing them to nullable ints should sort that issue too! Apologies - overlooked that one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.