解析csv文件时,如何定义特定字段是必需的。基本上,我想确保给定的字段永远不会为空,如果是,那么我想抛出一个异常。这是映射类:
public sealed class DataMapper : CsvClassMap<DataType>
{
public DataMapper()
{
Map(m => m.Field1).Name("FirstField");
Map(m => m.Field2).Name("SecondField");
Map(m => m.Field3).Name("ThirdField"); // this field should be mandatory
}
}
和用法:
List<DataType> data;
using (var sr = new StreamReader(localFilePath))
{
var reader = new CsvReader(sr);
reader.Configuration.RegisterClassMap<DataMapper>();
data = reader.GetRecords<DataType>().ToList();
}
目前我只是按如下方式检查数据列表中的结果:
var numberOfInvalidRecords = data.Count(data => string.IsNullOrEmpty(data.Field3));
if (nullAccountHolderRecords > 0)
{
//handle
}
我无法在CSVHelper文档中找到内置功能。我错过了什么吗?
答案 0 :(得分:5)
我可能会使用ConvertUsing
扩展程序执行此操作:
public sealed class DataMapper : CsvClassMap<DataType>
{
public DataMapper()
{
Map(m => m.Field1).Name("FirstField");
Map(m => m.Field2).Name("SecondField");
Map(m => m.Field3).ConvertUsing(row =>
{
if(string.IsNullOrEmpty(row.GetField<string>("ThirdField")))
throw new Exception("Oops, ThirdField is empty!");
return row.GetField<string>("ThirdField");
});
}
}
答案 1 :(得分:3)
以下是扩展API的解决方案:
public static class CsvHelperExtensions
{
public static CsvPropertyMap Required<T>(this CsvPropertyMap map, string columnName)
{
return map.Name(columnName).ConvertUsing(row =>
{
if (string.IsNullOrEmpty(row.GetField(columnName)))
throw new CsvParserException($"{columnName} is required, but missing from row {row.Row}");
return row.GetField<T>(columnName);
});
}
}
用法:
public CsvPersonMap()
{
Map(m => m.FirstName).Required<string>("First");
Map(m => m.LastName).Name("Last");
Map(m => m.MiddleName).Required<string>("Middle");
}
答案 2 :(得分:1)
As suggested by the creator of CsvHelper here:
目前,我认为你必须拥有 WillThrowOnMissingField = false并运行循环并检查您的具体情况 必填项目。你可以在之后查看标题 先阅读。
他的示例代码:
csv.WillThrowOnMissingField = false;
var list = new List<MyObject>();
var headerChecked = false;
while( csv.Read() )
{
if( !headerChecked )
{
// check for specific headers
if( !csv.FieldHeaders.Exists( "MyHeaderName" ) )
{
throw new Exception( "message" );
}
headerChecked = true;
}
list.Add( csv.GetRecord<MyObject>() );
}
答案 3 :(得分:0)
开发人员现在添加了一个Validate方法:https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/validation
使用它来针对非空或空字符串进行验证:
Map(m => m.Id).Validate(field => !string.IsNullOrEmpty(field));