本文介绍了FileHelpers在字段中引用和逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要用FileHelpers解析的csv文件,并且遇到这样的情况:引号和逗号都可以出现在字段中:

I have a csv file that I am parsing with FileHelpers and I have a situation where both a quote and a comma can appear in a field:

逗号:

323,"PC","28/02/2014","UNI001","5000",0,"Return","Returned Goods, damaged",88.00,15.40,"T1","N",0.00,"R","-",

报价

 148,"SI","13/01/2014","CGS001","4000",1,"5","17" Monitor",266.00,45.39,"T1","Y",311.39,"R","-", 

我的课程是:

[DelimitedRecord(",")]
public class Transaction
{
    public int TRAN_NUMBER;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string TypeText;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string DATE;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string TransactionAccount;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string NOMINAL_CODE;

    public int DEPT_NUMBER;

    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string INV_REF;

    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string DETAILS;

    public string NET_AMOUNT;
    public string TAX_AMOUNT;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string TaxCodeName;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string PAID_FLAG;

    public string AMOUNT_PAID;

    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string VatReconText;
    [FieldQuoted('"', QuoteMode.OptionalForBoth)]
    public string BankReconText;

    public string RECON_DATE;
}

我发现了该线程

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

但这仅能解决引号出现问题,而不有助于逗号。

But it only helps with quotes appearing problem and not the commas.

这两个问题都可以通过解决FileHelpers还是我应该寻找替代解决方案?

Can both of these problem be solved with FileHelpers or I should look for an alternative solution?

推荐答案

您可以实现 BeforeReadRecord

You can implement a BeforeReadRecord event to 'fix' your bad lines.

FileHelperEngine engine = new FileHelperEngine<Transaction>(); 
engine.BeforeReadRecord += BeforeEvent; 

private void BeforeEvent(EngineBase engine, BeforeReadRecordEventArgs e)
{
    var line = e.RecordLine;

    // you have to write the following replacement routine...
    var fixedLine = ReplaceEmbeddedCommasAndQuotesWithSomethingDifferent(line); 

    e.RecordLine = fixedLine; // replace the line with the fixed version
}

如果您希望在FileHelpers类本身中定义所有逻辑,则可以实现 INotifyRead< Transaction> 而不是使用事件。

If you prefer to define all the logic in the FileHelpers class itself, you can implement INotifyRead<Transaction> instead of using the event.

这篇关于FileHelpers在字段中引用和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:05