How to configure CSVHelper to ignore empty rows?
Prerequisites
- CSVHelper v30
- .NET 6+
TL;DR
When configuring CSVHelper, add the following configuration to the ShouldSkipRecord property:
1
2
3
4
5
var csvConfiguration =
new CsvConfiguration()
{
ShouldSkipRecord = args => args.Row.Parser.Record.All(string.IsNullOrWhiteSpace)
};
What is an empty row?
Given the following CSV file:
Header 1;Header 2;Header 3;
bla;1;2
;;;
Three;One;0
We want rows 3 and 4 to be ignored by CSVHelper.
By default, CSVHelper processes these rows and assigns empty values to each mapped property corresponding to the headers.
What configuration should be applied to ignore these rows?
When configuring CSVHelper, add the following configuration to the ShouldSkipRecord property:
1
2
3
4
5
var csvConfiguration =
new CsvConfiguration()
{
ShouldSkipRecord = args => args.Row.Parser.Record.All(string.IsNullOrWhiteSpace)
};
This tells CSVHelper that when every value in a row is empty or whitespace, the row should be skipped.
Sources
Have I already mentioned my favorite dev rule? Just in case, here it is again 🙂
you SHOULD apply the famous boy scout rule: you SHOULD leave the code cleaner than you found it.
This post is licensed under CC BY 4.0 by the author.