Home > OS >  Change CSV encoding from URI
Change CSV encoding from URI

Time:03-29

I am trying to download a CSV file and parse its fields and I am using the CSVHelper library (https://joshclose.github.io/CsvHelper). The issue which i face I think has to do with encoding, as when I read/print the file contents in my code the CsvHelper library can not find the relevant headers/fields. I imported the file in word and UTF8 seems to be the correct encoding in order to display the CSV contents correctly. However, my code and excel do not display the headers correctly (or any Czech characters) correctly. Here is how i am getting the excel:

var teamResultCsvUrl = new Uri("https://blabla/csv/4072");

And here is where i want to do my stuff:

        // 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();
                }
            }
            }

I am getting the following exception:

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)
.......

Also when I print the file contents, the characters are not encoded correctly. How/where can I set the encoding for the downloaded file? Is there anything else that looks wrong in my approach?

Thank you!

CodePudding user response:

CsvHelper does not control the encoding used to read the data. You can indicate the encoding to use when creating the StreamReader.

using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))

If Encoding.UTF8 doesn't work, you may need to figure out what the correct encoding is.

  • Related