I'm attempting to import a CSV file into a List in my code and initially, this was working fine, but I now need to modify this to allow null values for some of the DateTime fields (csvStartTime and csvEndTime).
using System;
using System.Linq;
using System.IO;
using System.Globalization;
private List<ColorDays> csvData;
csvData = new List<ColorDays>();
public List<T> GetData<T>(string file)
{
List<T> list = new List<T>();
var lines = GetCSVLines(file);
var headerLine = lines.First();
var columnNames = headerLine.Split(',');
var rows = lines.Skip(1);
var properties = typeof(T).GetProperties();
rows.ToList().ForEach(r =>
{
var cells = r.Split(',');
T obj = (T)Activator.CreateInstance(typeof(T));
int index = 0;
foreach (var columnName in columnNames)
{
var prop = properties
.SingleOrDefault(p =>p.Name == columnName);
Type propertyType = prop.PropertyType;
var value = cells[index++];
prop.SetValue(obj, Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture));
}
list.Add(obj);
});
return list;
}
public List<string> GetCSVLines(string file)
{
return File.ReadLines(file).ToList();
}
public class ColorDays
{
public DateTime csvDate { get; set; } //DT
public string csvWeekColor { get; set; }
public string csvDayColor { get; set; }
public string csvWeekDay { get; set; }
public string csvAorB { get; set; }
public DateTime csvStartTime { get; set; } //DT
public DateTime csvEndTime { get; set; } //DT
public string csvDirection { get; set; }
}
If I change the ColorDays class to nullable DateTime the parse fails.
Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=XXXXXXXXXXXX]]'.
I'm pretty new to parsing data and struggling to get my head around how to get this working. I was reading about using CsvHelper but I'm limited to what I can easily package up and followed this video which is where I got my current solution: https://www.youtube.com/watch?v=UsQ4hYw1TMQ
Any help is greatly appreciated.
Thanks.