gpt4 book ai didi

制表符分隔文件中的 C# FileHelpers 空值

转载 作者:太空狗 更新时间:2023-10-30 01:35:32 24 4
gpt4 key购买 nike

我正在使用 FileHelpers 解析制表符分隔的文件。

使用 FieldNullValue 属性后,空值被忽略,我以错误日志结尾

can't be found after the field 'filed name' at line 4 (the record has less fields, the delimiter is wrong or the next field must be marked as optional).

分隔符的类定义:

[DelimitedRecord("\t")]

字段都是具有相同属性的字符串:

 [FieldTrim(TrimMode.Both)]
[FieldNullValue("NULL")]
[FieldQuoted('"', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
public String initials;

在十六进制编辑器中查看导入的文件,我可以看到背靠背的制表符字符 (09 09),我认为这是一个空字段。

file line in hex view

如您在屏幕截图中所见,字段 5 和 9 为空。这些被 filehelper 解析器忽略。有谁知道为什么吗?

最佳答案

我认为您遇到了两个问题。

首先,FileHelpers 期待多一个选项卡。一个简单的解决方法是用 [FieldOptional] 属性标记最后一个字段。

其次,FieldNullValue("NULL")的意思是:如果文件中字段的值为null,则将其设置为字符串“NULL”。您的文件中的值为 "",而不是 null。如果需要将空值转换为其他值,可以使用 a custom converter如下:

public class MyEmptyFieldConverter : ConverterBase
{
protected override bool CustomNullHandling
{
/// you need to tell the converter not
/// to handle empty values automatically
get { return true; }
}

public override object StringToField(string from)
{
if (String.IsNullOrWhiteSpace(from))
return "NULL";
return from;
}
}

然后将属性添加到您的字段。

[FieldConverter(typeof(MyEmptyFieldConverter))]
public string field9;

关于制表符分隔文件中的 C# FileHelpers 空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25548698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com