2016-01-20 60 views
0

當文件的每一行有多個分隔符時,FileHelpers可以解析成一個對象嗎?下面是我需要使用FileHelpers從第三方數據提供商分析,樣本行如果可能的話:Filehelpers:每行中有多個分隔符?

ItemID=1000|VerificationResult=ERROR|VerificationResultCode=-101|VerificationResultDetail=Duplicate ItemID|ProfileID=|ACHRouting=|ACHAccount=|LastFourCC=4444|InvoiceNo=731-021-36-572|DateTime=1/20/2016 1:04:30 PM|CustomField1=|CustomField2= 

這本來是小事與FileHelpers如果數據提供了僅使用管道分隔符,但如你所見每個鍵/值對之間有一個「=」,然後每對之間的管道分隔符......嘆息。

回答

1

[FieldDelimiter]屬性允許您爲給定字段指定不同的分隔符。

另一種方法是爲關鍵值對編寫自己的轉換器。

public class KeyValuePairConverter : ConverterBase 
{ 
    private String _KeyName; 

    public KeyValuePairConverter(String keyName) 
    { 
     // needs a parameter to get the export correct 
     _KeyName = keyName; 
    } 

    public override object StringToField(string from) 
    { 
     // return everything after the last equals 
     // (you could choose to validate the first part of the string against the _KeyName) 
     return from.Substring(from.LastIndexOf('=') + 1);; 
    } 

    public override string FieldToString(object fieldValue) 
    { 
     return String.Format("{0}={1}", _KeyName, fieldValue); 
    } 
} 

,然後你的字段的定義是這樣的

[FieldConverter(typeof(KeyValuePairConverter), "ItemID")] 
    public String ItemID; 
+0

感謝shamp00!我不使用filehelpers足以知道我可以覆蓋並創建我自己的轉換器。這很完美,謝謝。 – Jeff