【发布时间】:2019-03-09 19:19:44
【问题描述】:
C#中CsvHelper解析小数的问题。
我创建了一个从 byte[] 而不是文件获取 csv 文件的类,它可以正常工作。
public static List<Topic> GetAll(byte[] attachmentBytes)
{
using (Stream stream = new MemoryStream(attachmentBytes))
{
using (var reader = new StreamReader(stream, Encoding.GetEncoding(1252), true))
{
using (var csv = new CsvReader(reader))
{
csv.Configuration.Delimiter = ";";
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
return csv.GetRecords<Topic>().ToList();
}
}
}
}
如您所见,我添加了将 csv 映射到对象的类:
public class Topic
{
[Name("ID")]
public int Id { get; set; }
[Name("description")]
public string Description { get; set; }
[Name("DecimalPTS")]
public decimal? DecimalPts { get; set; }
}
这就是我的示例 csv 数据的样子。
ID;description;DecimalPTS
1;singing;0,6
2;speaking;2,6
3;working;3,3
但是这个解决方案会产生错误
CsvHelper.TypeConversion.TypeConverterException : The conversion cannot be performed.
Text: '0,6'
MemberType: System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
当我替换时,只需执行 Replace(',','.');在输入时,本地测试通过,但在我的服务器上测试失败(似乎我在本地和服务器上有不同的文化)
我试图解决这个问题的方法:
- 我加了
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture; - 我用
7.1.1CSV版本,但是改成12.1.2,还是一样的错误
不幸的是,没有任何帮助。
【问题讨论】:
标签: c# .net csv decimal csvhelper