如何跳过不良记录

时间:2012-01-15 00:14:00

标签: c# datetime filehelpers

我正在使用 File Helpers 2.9.9 ,我想知道如何让它跳过错误的记录而不是崩溃?

object[] transactions = engine.ReadStream(textReader); // will crash if one record fails.

我也遇到了DateTime.I无法理解为什么它无法使用我设置的格式转换为“12/22/2011”。

Error Converting '"12/22/2011"' to type: 'DateTime'.  does not match any of the given formats: 'MM/dd/yyyy', 'MM/d/yyyy', 'M/d/yyyy'
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: FileHelpers.ConvertException: Error Converting '"12/22/2011"' to type: 'DateTime'.  does not match any of the given formats: 'MM/dd/yyyy', 'MM/d/yyyy', 'M/d/yyyy'

2 个答案:

答案 0 :(得分:4)

1) [编辑] - 我错了,您可以将engine.ErrorManager.ErrorMode设置为SaveAndContinue - 请参阅示例@ http://www.filehelpers.com/example_errorhandling.html

2)基于包含带双引号的字符串的单引号,我想问题是您需要提供FieldQuoted属性 - 请参阅http://www.filehelpers.com/attributes.html

答案 1 :(得分:3)

您可以使用BeforeReadRecord event来解析记录行,并为您需要跳过的任何记录设置skipThisRecord = True。例如:

FileHelperEngine engine = new FileHelperEngine(typeof(Orders)); 
// set the event here
engine.BeforeReadRecord += new BeforeReadRecordHandler(BeforeEvent); 

然后事件本身:

private void BeforeEvent(EngineBase engine, BeforeReadRecordEventArgs e)
{
    // skip any bad lines
    if (e.RecordLine.StartsWith(" ") || e.RecordLine.StartsWith("-"))
        e.SkipThisRecord = true;
}

在上面的示例中,将跳过任何以空格或“ - ”开头的记录,但您可以应用所需的任何逻辑。您可以使用e.RecordLine.Split(',')将当前行拆分为列值数组,然后使用DateTime.TryParse()确定日期字符串是否有效。

相关问题