I have the following code to fill my datatable before a sqlbulkcopy:
Using (StreamReader readerDatatable = new StreamReader(filePath, Encoding.UTF8))
using (CsvReader csvReaderDatatable = new CsvReader(readerDatatable, csvConfig))
using (CsvDataReader dataReader = new CsvDataReader(csvReaderDatatable))
using (var dt = new DataTable())
{
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<string>().NullValues.Add("NULL");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<DateTime?>().NullValues.AddRange(new[] { "NULL", "0", "N/A" });
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<float?>().NullValues.Add("NULL");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<float?>().NullValues.Add("NA");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<float?>().NullValues.Add("N/A");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<decimal?>().NullValues.Add("NULL");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<decimal?>().NullValues.Add("NA");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<decimal?>().NullValues.Add("N/A");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanFalseValues.Add("0");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.Add("NA");
csvReaderDatatable.Context.TypeConverterOptionsCache.GetOptions<bool>().BooleanTrueValues.Add("1");
var bulkCopy = new SqlBulkCopy("Data Source=test;Initial Catalog=test;Trusted_Connection=True;");
dt.Load(dataReader);
}
The datatable is correctly populated. However the empty values (,,) are converted as empty strings ('') which makes an error when I do the bulkcopy WriteToServer (String can not be converted to real).
I thought that the TypeConverterOptionsCache would have solved my problem but it is not.
How can I make sure that empty values in the csv file remain null in the datatable.
Thank you