FileHelpers嵌套引号和逗号 - 解析错误 [英] FileHelpers nested quotes and commas - parsing error

查看:186
本文介绍了FileHelpers嵌套引号和逗号 - 解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我无法处理一行表单:

我尝试使用一个非常棒的FileHelpers库解析一个来自地狱的CSV文件。

 TOYS RUS,INC。,fld2,fld3,< numberThousands>,< numberThousands> ;,< numberThousands>,fld7,

FileHelper非常适合处理数字字段'千'格式(使用自定义格式化程序),即使用引号,尾随逗号等包装,但是它会导致第一个字段出现问题。

 TOYS RUS,INC。,fld2,... 

此字段包括嵌套引号和嵌套逗号。 FileHelper不知道如何处理这个,并将其分割成两个单独的字段,这随后会导致抛出异常。



有任何推荐的方法来处理?

解决方案

首先,您需要将所有字段都选择性引用。

  [DelimitedRecord(,)] 
public class contactTemplate
{
[FieldQuoted('',QuoteMode.OptionalForBoth)]
public string CompanyName;
[FieldQuoted('',QuoteMode.OptionalForBoth)]
public string fld2;
// etc ...
}

BeforeReadRecord 事件中的其他分隔符(例如,单引号)。

  var engine = new FileHelperEngine< MyFileHelpersSpec>(); 

engine.BeforeReadRecord + =(sender,args)=>
args.RecordLine = args.RecordLine.Replace(@,');


I'm trying to parse a CSV file from hell, using the fantastic FileHelpers library.

It's failing to handle a row of the form:

"TOYS R"" US"," INC.""",fld2,fld3,"<numberThousands>","<numberThousands>","<numberThousands>",fld7,

FileHelper is very good at handling number fields in 'thousands' format (using a custom formatter), even when wrapped in quotes, trailing commas etc, however it's causing issues with the first field.

"TOYS R"" US"," INC.""",fld2,...

This field includes both nested quotes and nested commas. FileHelper doesn't know how to handle this and is splitting it into two separate fields, which subsequently causes an exception to be thrown.

Are there any recommended ways to handle this?

解决方案

First, you need to make all of your fields optionally quoted.

[DelimitedRecord(",")] 
public class contactTemplate
{
  [FieldQuoted('"', QuoteMode.OptionalForBoth)]
  public string CompanyName;
  [FieldQuoted('"', QuoteMode.OptionalForBoth)]
  public string fld2;
  // etc...
}

Then you need replace the escaped delimiters with something else (e.g., a single quote) in a BeforeReadRecord event.

var engine = new FileHelperEngine<MyFileHelpersSpec>();

engine.BeforeReadRecord += (sender, args) => 
    args.RecordLine = args.RecordLine.Replace(@"""", "'");

这篇关于FileHelpers嵌套引号和逗号 - 解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆