public interface ICsvProductReaderConfigurationFactory
{
Configuration Build();
}
public class CsvProductReaderConfigurationFactory : ICsvProductReaderConfigurationFactory
{
private readonly ClassMap<ProductDto> classMap;
public CsvProductReaderConfigurationFactory(IProductDtoClassMapProvider classMapProvider)
{
classMap = classMapProvider.Get();
}
public Configuration Build()
{
var config = new Configuration
{
Delimiter = "\t",
HasHeaderRecord = true,
IgnoreQuotes = true,
MissingFieldFound = (rows, fieldIndex, readingContext) =>
Log.Warn($"Missing Field Found at line {readingContext.Row}\r\n" +
$"Field at index {fieldIndex} does not exist\r\n" +
$"Raw record: {readingContext.RawRecord}"),
BadDataFound = context =>
Log.Warn($"Bad data found at row {context.Row}\r\n" +
$"Raw data: {context.RawRecord}")
};
config.RegisterClassMap(classMap);
return config;
}
}
public interface ICvsProductReader
{
IEnumerable<ProductDto> GetAll(string filePath);
}
public class CvsProductReader : ICvsProductReader
{
private readonly ICsvProductReaderConfigurationFactory csvProductReaderConfigurationFactory;
public CvsProductReader(ICsvProductReaderConfigurationFactory csvProductReaderConfigurationFactory)
{
this.csvProductReaderConfigurationFactory = csvProductReaderConfigurationFactory;
}
public IEnumerable<ProductDto> GetAll(string filePath)
{
var csvReaderConfiguration = csvProductReaderConfigurationFactory.Build();
using (var streamReader = new StreamReader(filePath))
using (var csvReader = new CsvReader(streamReader, csvReaderConfiguration))
{
return csvReader.GetRecords<ProductDto>().ToArray();
}
}
}
MissingFieldFound
属性会在发现缺失字段时被调用,但不会影响结果。
我想知道是否可以配置 CsvHelper 跳过缺失字段的行。
s
的GetRecord
还是GetRecords
? - Drag and DropMissingFieldFound
设置为null只会关闭抛出异常,而不会过滤结果。 - Makrushin Evgenii