【发布时间】:2020-09-03 13:28:57
【问题描述】:
我正在使用 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.
我在文档中找不到任何内容。我希望空字段默认为 0。
我的代码:
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;
}
【问题讨论】: