I want to use CsvReader and CsvDataReader to load the input CSV into a DataTable, where the colums in the destination data table defines the data types. But for columns e.g. of int type, the CSV parsing fails when an empty string (;;) is found in a CSV field.
How can i specify default int value (0) for the Credits column when empty string is found in the CSV input?
// Construct the datatable
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Name", typeof(string)));
dataTable.Columns.Add(new DataColumn("Credits", typeof(int)));
dataTable.Columns.Add(new DataColumn("Notes", typeof(string)));
dataTable.Columns.Add(new DataColumn("LastLogin", typeof(DateTime)));
dataTable.Columns.Add(new DataColumn("Balance", typeof(decimal)));
// Prepare CSV content
StringBuilder sbInput = new StringBuilder();
sbInput.AppendLine("Name;Credits;Notes;LastLogin;Balance");
sbInput.AppendLine("Michael;2433;Good guy;2023-03-28;736,26");
sbInput.AppendLine("John;;Bad guy;2023-04-01;-49,25");
// Prepare the configuration
CsvConfiguration csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
{
NewLine = Environment.NewLine,
Delimiter = ";",
Mode = CsvMode.NoEscape,
TrimOptions = TrimOptions.Trim,
UseNewObjectForNullReferenceMembers = true
};
// Read the CSV stream
using (var csvReader = new CsvReader(new StringReader(sbInput.ToString()), csvConfiguration))
{
using (var csvDataReader = new CsvDataReader(csvReader))
{
// Following exception thrown if John;;Bad guy
// Input string was not in a correct format.Couldn't store <> in Credits Column. Expected type is Int32.
dataTable.Load(csvDataReader);
}
}