我正在尝试下载CSV文件并解析其字段,我正在使用CSVHelper库(https://joshclose.github.io/CsvHelper)。我认为我面临的问题与编码有关,因为当我读取/打印代码中的文件内容时,CsvHelper库找不到相关的头/字段。我用word导入了文件,为了正确显示CSV内容,UTF8似乎是正确的编码。但是,我的代码和excel不能正确显示标题(或任何捷克字符(。以下是我如何获得优异成绩:
var teamResultCsvUrl = new Uri("https://blabla/csv/4072");
这是我想做的事情:
// total results for teams
using (response = await client.GetAsync(teamResultCsvUrl))
{
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
using (StreamReader streamReader = new StreamReader(stream))
using (CsvHelper.CsvReader csvReader = new CsvHelper.CsvReader(streamReader, CultureInfo.InvariantCulture))
{
teamCsvResults = csvReader.GetRecords<ValidationClass>().ToList();
}
}
}
我得到以下异常:
System.AggregateException: One or more errors occurred.
CsvHelper.HeaderValidationException: Header with name '<SOME HEADER>' was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.
at CsvHelper.Configuration.ConfigurationFunctions.HeaderValidated(Boolean isValid, String[] headerNames, Int32 headerNameIndex, ReadingContext context)
at CsvHelper.CsvReader.ValidateHeader(ClassMap map)
at CsvHelper.CsvReader.ValidateHeader(Type type)
at CsvHelper.CsvReader.ValidateHeader[T]()
at CsvHelper.CsvReader.<GetRecords>d__63`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
.......
此外,当我打印文件内容时,字符编码不正确。如何/在哪里可以为下载的文件设置编码?在我的方法中还有什么看起来不对的地方吗?
谢谢!
CsvHelper
不控制用于读取数据的编码。您可以指示创建StreamReader
时要使用的编码。
using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
如果Encoding.UTF8
不起作用,您可能需要弄清楚正确的编码是什么