c# - 阅读时如何忽略CSV中的空行

标签 c# csv csvhelper

尝试使用 CsvHelper.GetRecords<T>() 读取具有空行(通常在末尾)的 CSV 文件.

如果没有空行,这是一种享受。但是,如果 CSV 文件有一个空行(定义为 , , , , , ),则它会抛出 TypeConverterException

Text: ''
MemberType: IntelligentEditing.PerfectIt.Core.DataTypes.Styles.StyleRuleType
TypeConverter: 'CsvHelper.TypeConversion.EnumConverter'

我已经阅读了文档( https://joshclose.github.io/CsvHelper/api/CsvHelper.Configuration/Configuration/ )并尝试将配置对象设置为 IgnoreBlankLines = true然而这并没有奏效。

简化为一个例子:

public enum ItemTypeEnum
{
    Unknown = 0,
    Accounts = 1,
    HR = 2,
}


public class CsvItemDto
{
    public int Id { get; set; }

    public string Value { get; set; }

    public ItemTypeEnum ItemType { get; set; }
}

.
.
.
var configuration = new Configuration()
{
    HasHeaderRecord = true,
    HeaderValidated = null,
    MissingFieldFound = null,
    IgnoreBlankLines = true,

};
var csv = new CsvReader(textReader, configuration);
var rows = csv.GetRecords<CsvItemDto>();


if (rows != null)
{
    var items = rows.ToList();
    //Throws exception here
}


CSV 通常包含如下内容:
Id,Value,ItemType
1,This,Unknown
2,That,Accounts
3,Other,HR
,,
,,

我期待 IgnoreBlankLines忽略 CSV 中的空白行,但事实并非如此。有任何想法吗?

最佳答案

@phat.huynh 有正确的想法。只需告诉它跳过所有字段都是空字符串的任何记录。

var configuration = new Configuration()
{
    HasHeaderRecord = true,
    HeaderValidated = null,
    MissingFieldFound = null,
    ShouldSkipRecord = record => record.Record.All(string.IsNullOrWhiteSpace)
};

关于c# - 阅读时如何忽略CSV中的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990749/

相关文章:

c# - 从 C# 中的 .docx 文件的页眉和页脚获取图像

c# - 当传递具有修改行的 DataRow 集合时,更新需要有效的 UpdateCommand

c# - 如何在 C# 中仅引发 1 个计时器事件?

r - 为什么 R 将 UTF-8 header 读取为文本?

c# - CsvHelper 抛出 CsvMissingFieldException

.net-core - 未识别为有效的日期时间

c# - 如何处理使用 CsvHelper 解析时的空列?

用于搜索术语文本的 C# 代码/算法

java - 使用 Java 将 CSV 文件加载到 MySQL 服务器

python - Pandas - 去除空白