In CsvHelper how to catch a conversion error and know what field and what row it happened in?

跟風遠走 提交于 2019-12-01 02:06:14
Josh Close

Currently, there is no way to ignore errors at the field/property level. Your current options are these:

Look at the exception data.

catch( Exception ex )
{
    // This contains useful information about the error.
    ex.Data["CsvHelper"];
}

Ignore reading exceptions. This is on a row level, though, not field. It will allow the whole file to still be read, and just ignore the rows that don't work. You can get a callback when an exception occurs.

csv.Configuration.IgnoreReadingExceptions = true;
csv.Configuration.ReadingExceptionCallback = ( ex, row ) =>
{
    // Do something with the exception and row data.
    // You can look at the exception data here too.
};

First of all, it seems that I need to catch CsvTypeConverterException.

 while (csv.Read())
    {
       try
       {    
          var record = csv.GetRecord<MyType>();    
       }
       catch (CsvTypeConverterException ex)
       {
         //ex.Data.Values has more info...
       }
    }

I now know how to investigate what went wrong, but how do I make sure that that field is skipped but the rest of the fields in that row are converted, so that not the entire row is thrown away?

Thanks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!