CsvHelper 28.0.0及以上版本如何跳过空白行?
CsvHelper 28.0.0+ 跳过空白行的推荐实现方案
CsvHelper 28.0.0 版本对ShouldSkipRecordArgs类型做了API调整:原string[] Record属性被替换为IReaderRow Row类型,且IReaderRow未实现IEnumerable接口,旧版本通过x => x.Record.All(field => string.IsNullOrWhiteSpace(field))跳过空白行的写法会直接编译失效。
28.0.0及以上版本推荐直接利用IReaderRow公开的ColumnCount属性和索引器遍历所有字段做判断,不需要依赖额外的内部API或者反射,实现代码如下:
using System.Globalization; using CsvHelper; using CsvHelper.Configuration; var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture) { ShouldSkipRecord = args => { // 逐列校验当前行,存在任意非空白字段则保留行 for (int colIndex = 0; colIndex < args.Row.ColumnCount; colIndex++) { if (!string.IsNullOrWhiteSpace(args.Row[colIndex])) { return false; } } // 所有字段均为空/空白,跳过当前行 return true; } };
如果偏好LINQ写法,也可以通过生成列索引序列的方式复用All判断逻辑,效果和直接遍历一致:
ShouldSkipRecord = args => Enumerable.Range(0, args.Row.ColumnCount) .Select(colIndex => args.Row[colIndex]) .All(string.IsNullOrWhiteSpace)
注意:不要通过反射获取
IReaderRow内部存储的记录数组做判断,内部字段可能在后续小版本中变更,会带来版本兼容风险。
内容的提问来源于stack exchange,提问作者r.straughan
相关产品推荐
相关产品推荐

