问题描述
我正在使用CsvHelper解析我的CSV文件。 在我的CSV中,我有一列包含一个双精度值,但是csv生成工具可以将其创建为空字段。
示例CSV
Name,Value,Date
Jim;1.23;20200901
John;;20200901
Jim的Value字段工作正常,但是当到达空值的John时,出现以下异常。
The conversion cannot be performed.
Text: ''
MemberType: System.Double
TypeConverter: 'CsvHelper.TypeConversion.DoubleConverter'
An unexpected error occurred.
我的代码:
public class Transaction
{
public string Name { get; set; }
public double Value { get; set; }
public DateTime Date { get; set; }
}
在这种情况下,我像var result = ParseCsvZipArchiveEntry<Transaction>(zipArchiveEntry);
private List<T> ParseCsvZipArchiveEntry<T>(ZipArchiveEntry zipArchiveEntry) where T : class
{
string TempFilePath = Path.GetTempFileName();
List<T> Result = null;
try
{
zipArchiveEntry.ExtractToFile(TempFilePath,true);
CsvHelper.Configuration.CsvConfiguration Config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
Config.Delimiter = ";";
using (var reader = new StreamReader(TempFilePath))
using (var csv = new CsvReader(reader,Config))
{
Result = csv.GetRecords<T>().ToList();
}
}
catch (Exception ex)
{
Logger(ex.Message);
}
finally
{
if(File.Exists(TempFilePath))
File.Delete(TempFilePath);
}
return Result;
}
解决方法
您可以将Default
属性应用于模型中的属性。它被广告为The default value that will be used when reading when the CSV field is empty.
using CsvHelper.Configuration.Attributes;
public class Transaction
{
public string Name { get; set; }
[Default(0)] // set to 0 when the field is empty
public double Value { get; set; }
public DateTime Date { get; set; }
}
在我的测试中,这将返回2个事务实例的列表,其中第二个实例的Value
为0。
该属性的API文档为found here。