我如何找出哪些列的值无效

时间:2019-01-29 09:50:38

标签: c# csvhelper formatexception

我正在使用CsvHelper解析CSV文件,包括类型转换,例如到DateTime。

当单元格值的格式无效时,我得到

while (CsvReader.Read())
{
    var record = CsvReader.GetRecord<TModel>();
    csvReader.GetRecord<MyModel>(); //throws following exception:

    // CsvHelper.ReaderException: 'An unexpected error occurred.'
    // Inner Exception
    //
    // FormatException: The string 'a' was not recognized as a valid DateTime. There is an unknown word starting at index '0'.

如何查找无法解析的单元格的HeaderName或MyModel的属性。

2 个答案:

答案 0 :(得分:1)

您应该尝试一下,并在捕获中使用来获取行和索引

remote:  !     https://devcenter.heroku.com/articles/ruby-support#supported- 
runtimes
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to morning-plains-67699.
remote: 
To https://git.heroku.com/morning-plains-67699.git
! [remote rejected] master -> master (pre-receivehook declined)
error: failed to push some refs to 'https://git.heroku.com/morning-plains- 
67699.git'

然后您可以使用标题记录获取字段

int index = csvReader.Context.CurrentIndex; // zero based
int row = csvReader.Context.Row;          // 1 based

答案 1 :(得分:0)

要添加它,这是我的方法

catch (ReaderException e)
{                   
    string notification = $"The field { e.ReadingContext.HeaderRecord[e.ReadingContext.CurrentIndex] } has the invalid value { e.ReadingContext.Record[e.ReadingContext.CurrentIndex] }";                   
}