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.TypeConverterobject for your Nullable types. Note that I'm going to useintsince 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
CsvConfigurationobject with all of my settings prior to constructing myCsvReaderobject.Then you can call
myReader = new CsvReader(stream, csvConfig)to build theCsvReaderobject.IF you need to have defined values for null such as
"NA" == nullthen you will need to roll your ownCsvHelper.TypeConversionclass. I recommend that you extend theNullableConverterclass to do this and override both the constructor andConvertFromStringmethod. Using blank values as null is really your best bet though.