var csv =
from line in File.ReadAllLines("C:/file.csv")
let customerRecord = line.Split(',')
select new Customer()
{
contactID = customerRecord[0],
surveyDate = customerRecord[1],
project = customerRecord[2],
projectCode = customerRecord[3]
};
public class Customer
{
public string contactID { get; set; }
public string surveyDate { get; set; }
public string project { get; set; }
public string projectCode { get; set; }
}
I’d like to be able to read the surveyDate as a DateTime in order to compare it with other DateTime fields I’m joining to the csv file.
I’ve tried just setting surveyDate as Date.Time in the class, and I’ve tried converting it in the select statement, but both fail with the following error:
FormatException: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
I do have to work with the csv file, so I can’t add the data to sql server.
contactID,responseDate,project,projectID
1,6/4/2009,0-3 months,1
2,6/11/2009,0-3 months,1
Right… Because you can never know what the input will be from the CSV you can’t always try and implicitly convert the string to a DateTime and because you want to do the convert of a string within the select a way to do this is an extension method.
Then when you want to convert in the select do it like this:
You have your own method. Hope this helps and works for you.
The string you want to parse will be passed to the method and then you can handle it and return a valid date time, handling incorrect inputs.
http://msdn.microsoft.com/en-us/library/bb383977.aspx
See this link for an explanation