简体   繁体   English

使用FileHelpers导入CSV文件时,为什么应将类模型的最后一列标记为可选?

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

I read many questions here on StackOverflow trying to find a solution to a simple problem. 我在StackOverflow上阅读了许多问题,试图找到一个简单问题的解决方案。 I'm importing a CSV file using FileHelpers library. 我正在使用FileHelpers库导入CSV文件。 The CSV file has no delimiter at the last column, and when I try to import I get the error 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)

It's right, because my file looks like 是的,因为我的文件看起来像

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

One solution I found is to mark the last column using attribule FieldOptional . 我发现的一种解决方案是使用属性FieldOptional标记最后一列。 The problem is that the column isn't optional; 问题在于该列不是可选的。 it must throw an error if the last column is null. 如果最后一列为空,则必须抛出错误。

How can I handle this situation avoiding ' FieldOptional ' attribute? 如何避免使用“ FieldOptional ”属性来处理这种情况?

Which version are you using? 您正在使用哪个版本? With FileHelpers 3.1.5, this works fine: 使用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();
    }
}

With older versions (2.0 if I remember correctly), you needed to add one more extra (dummy) property and mark it [FieldOptional] . 对于较旧的版本(如果我没记错的话是2.0),您需要再添加一个额外的(虚拟)属性并将其标记为[FieldOptional] This means: the last delimiter is optional and I don't care about any contents after the last delimiter . 这意味着: 最后一个定界符是可选的,我不在乎最后定界符之后的任何内容

So your class would then look like this: 这样您的课程将如下所示:

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

This class also works with the above example. 此类也适用于以上示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM