I was wondering if CsvHelper by Josh Close has anything in the configuration I am missing to translate values to null. I am a huge fan of this library, but I always thought there should be some sort of configuration to let it know what values represent NULL in your file. An example would be a column with the value "NA", "EMPTY", "NULL", etc. I am sure I could create my own TypeConverter, but I was hoping there would be an easier option to set somewhere in a config as this tends to be fairly common with files I encounter.
Is there a configuration setting to do this relatively easily?
I found the TypeConversion in the CsvHelper.TypeConversion namespace but am not sure where to apply something like this or an example of the correct usage:
new NullableConverter(typeof(string)).ConvertFromString(new TypeConverterOptions(), "NA")
I am also using the latest version 2.2.2
Thank you!
CsvHelper can absolutely handle nullable types. You do not need to roll your own TypeConverter if a blank column is considered null. For my examples I am assuming you are using user-defined fluent mappings.
The first thing you need to do is construct a
CsvHelper.TypeConverter
object for your Nullable types. Note that I'm going to useint
since strings allow null values by default.Next is setting the attribute on your CsvReader object to allow blank columns & auto-trim your fields. Personally like to do this by creating a
CsvConfiguration
object with all of my settings prior to constructing myCsvReader
object.Then you can call
myReader = new CsvReader(stream, csvConfig)
to build theCsvReader
object.IF you need to have defined values for null such as
"NA" == null
then you will need to roll your ownCsvHelper.TypeConversion
class. I recommend that you extend theNullableConverter
class to do this and override both the constructor andConvertFromString
method. Using blank values as null is really your best bet though.