带日期时间的 CSVHelper FormatException

CSVHelper FormatException with DateTime

我遇到的问题尤其与 CSVHelper 库有关。

我的 csv 文件看起来像这样:

Number,Date,Account,Amount,Subcategory,Memo
 ,09/05/2017,XXX XXXXXX,-29.00,FT , [Sample string]
 ,09/05/2017,XXX XXXXXX,-20.00,FT ,[Sample string]
 ,08/05/2017,XXX XXXXXX,-6.30,PAYMENT,[Sample string]

我用 CSVHelper 做的是这样的:

        List<Transaction> result = new List<Transaction>();
        using (TextReader fileReader = File.OpenText("data.csv"))
        {
            var csv = new CsvReader(fileReader);
            result = csv.GetRecords<Transaction>().ToList();
        }

问题是当它试图在最后一行执行 GetRecord 时,我得到这个异常:

Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
   at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles)
   at CsvHelper.TypeConversion.DateTimeConverter.ConvertFromString(TypeConverterOptions options, String text)
   at lambda_method(Closure )
   at CsvHelper.CsvReader.CreateRecord[T]()
   at CsvHelper.CsvReader.<GetRecords>d__65`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

如您所见,数据存在一些问题 - 第一列为空或字符串为空。即便如此,异常消息仍指向第二列日期的问题。

如有任何帮助,我们将不胜感激。

我猜您的默认区域性指定的日期格式与 CSV 文件中的日期格式不同。尝试将区域性设置为与数据匹配的区域性。

    var csv = new CsvReader(fileReader);
    csv.Configuration.CultureInfo = CultureInfo.GetCultureInfo("en-GB");
    result = csv.GetRecords<Transaction>().ToList();

Fiddle: https://dotnetfiddle.net/iTvc4Y