簡體   English   中英

使用FileHelpers導入CSV文件時,為什么應將類模型的最后一列標記為可選?

[英]Why should I mark the last column of class model as optional when importing a CSV file with FileHelpers?

我在StackOverflow上閱讀了許多問題,試圖找到一個簡單問題的解決方案。 我正在使用FileHelpers庫導入CSV文件。 CSV文件的最后一列沒有定界符,當我嘗試導入時出現錯誤

Line: 2 Column: 179. Delimiter ',' not found after field 'Active' (the record has less fields, the delimiter is wrong or the next field must be marked as optional)

是的,因為我的文件看起來像

...,Clip Ons,,D02,8 Card Wallet,Y
...,D02,Bathurst Chain Crossbody,Y

我發現的一種解決方案是使用屬性FieldOptional標記最后一列。 問題在於該列不是可選的。 如果最后一列為空,則必須拋出錯誤。

如何避免使用“ FieldOptional ”屬性來處理這種情況?

您正在使用哪個版本? 使用FileHelpers 3.1.5,可以正常工作:

[DelimitedRecord(",")]
[IgnoreEmptyLines]
public class MySpec
{
    public string Column1;
    public string Column2;
    public string Column3;
    public string Column4;
    public string Column5;
}

class Program
{
    static void Main(string[] args)
    {
        var fileHelpersEngine = new FileHelperEngine<MySpec>();
        var records = fileHelpersEngine.ReadString("Clip Ons,,D02,8 Card Wallet,Y");
        var firstRecord = records.First();
        Assert.AreEqual("Clip Ons", firstRecord.Column1);
        Assert.AreEqual(string.Empty, firstRecord.Column2);
        Assert.AreEqual("D02", firstRecord.Column3);
        Assert.AreEqual("8 Card Wallet", firstRecord.Column4);
        Assert.AreEqual("Y", firstRecord.Column5);
        Console.ReadKey();
    }
}

對於較舊的版本(如果我沒記錯的話是2.0),您需要再添加一個額外的(虛擬)屬性並將其標記為[FieldOptional] 這意味着: 最后一個定界符是可選的,我不在乎最后定界符之后的任何內容

這樣您的課程將如下所示:

[DelimitedRecord(",")]
[IgnoreEmptyLines]
public class MySpec
{
    public string Column1;
    public string Column2;
    public string Column3;
    public string Column4;
    public string Column5;
    [FieldOptional]
    public string Dummy;
}

此類也適用於以上示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM