[英]Parse csv to decimal on different cultures using CsvHelper in c#
Problem with parsing decimals by CsvHelper in c#. 在C#中由CsvHelper解析小数的问题。
I created a class that get csv file from byte[] istead of file, and it works correctly. 我创建了一个从byte []而不是file获取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();
}
}
}
}
Like you can see I added class to map csv to object: 如您所见,我添加了类以将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; }
}
And this is how my example csv data looks like. 这就是我的示例csv数据的样子。
ID;description;DecimalPTS
1;singing;0,6
2;speaking;2,6
3;working;3,3
But this solution produces an error with 但是此解决方案会产生错误
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]]
When I replaced just do Replace(',','.'); 当我替换时,只需执行Replace(',','。'); on input, localy test pass, but on my server test fails (seems like I have different culture localy, and on the server)
在输入中,通过区域设置测试通过,但是在我的服务器上测试失败(似乎我在服务器上具有不同的区域性语言设置)
What I tried to fix this issue: 我试图解决的问题:
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
csv.Configuration.CultureInfo = CultureInfo.InvariantCulture;
7.1.1
CSV Version, but changed to 12.1.2
, and still the same error 7.1.1
CSV版本,但更改为12.1.2
,仍然是相同的错误 Unfortunately, nothing helped. 不幸的是,没有任何帮助。
Try to set your culture to de-DE
尝试将您的文化设为
de-DE
csv.Configuration.CultureInfo = new CultureInfo("de-DE");
You can do one more trick that, if your application works on 如果您的应用程序可以运行,您可以再做一个技巧
en-US
and if it's on a en-US
(如果是在美国) de-DE
. de-DE
。 or vice versa. 或相反亦然。
Demo: 演示:
var bytes = File.ReadAllBytes(@"Path to your csv file");
List<Topic> list = GetAll(bytes);
//Print list item to console
foreach (var item in list)
{
Console.WriteLine($"ID: {item.Id}\t Description: {item.Description}\t DecimalPTS: {item.DecimalPts}");
}
Output: 输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.