CodexBloom - Programming Q&A Platform

Issues Parsing CSV with Mixed Data Types in C# - Converting Strings to Dates and Integers

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-07
csv parsing CsvHelper C#

I'm maintaining legacy code that I'm having trouble parsing a CSV file in C# where some columns have mixed data types... For example, the first column can contain dates or text, and the second column can hold integers or strings. I am using the CsvHelper library (version 15.0.4) to handle the parsing, but I'm running into issues with converting the string values into their respective data types correctly. Here's a snippet of the CSV file: ``` Date,Value "2023-10-01",123 "Invalid Date",456 "2023-09-30", "Some Text" "2023-09-29",789 ``` And this is my code for parsing: ```csharp using CsvHelper; using CsvHelper.Configuration; using System.Globalization; using System.IO; public class Record { public DateTime? Date { get; set; } public object Value { get; set; } } public class RecordMap : ClassMap<Record> { public RecordMap() { Map(m => m.Date).ConvertUsing(row => { DateTime tempDate; if (DateTime.TryParse(row.GetField(0), out tempDate)) return tempDate; return null; }); Map(m => m.Value).ConvertUsing(row => { int tempInt; if (int.TryParse(row.GetField(1), out tempInt)) return tempInt; return row.GetField(1); }); } } public void ParseCsv(string path) { using (var reader = new StreamReader(path)) using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture))) { csv.Context.RegisterClassMap<RecordMap>(); var records = csv.GetRecords<Record>().ToList(); } } ``` When I run this code, I get the following behavior for the row with "Invalid Date": `CsvHelper.CsvReaderException: 'Bad data found on row 2, column 1. Field: Invalid Date'`. I need to handle rows where the date might be invalid without causing the entire parsing process to unexpected result. Additionally, I want to ensure that any non-integer values in the Value column are returned as strings instead of causing an exception. What would be the best way to modify my parsing logic to handle these scenarios gracefully? For context: I'm using C# on Ubuntu. What's the best practice here? Cheers for any assistance!