JoshClose / CsvHelper

Library to help reading and writing CSV files
http://joshclose.github.io/CsvHelper/
Other
4.72k stars 1.06k forks source link

Conversion can not be performed #410

Closed vinaypatelce closed 9 years ago

vinaypatelce commented 9 years ago

Hello,

I'm getting error "Conversion can not be performed" while trying to get records from csv response.

Csv response example

Title;Description;Count
Title 123;do & don't;3

Below is my code section.

using (var reader = new StreamReader(resposneStream))
{
    using (var csv = new CsvReader(reader))
    { 
        csv.Configuration.Delimiter = ";";
        csv.Configuration.RegisterClassMap<TColumnMap>();
        var records = csv.GetRecords<TRecord>().ToList();
        return records;
    }
}

Here i have ";" in description filed value so while parsing with Delimiter ";" i'm getting error.

How can i handle this issue?

JoshClose commented 9 years ago

What is the class definition for TRecord?

I can already see one problem with your data. The header row has 3 columns, but the data row has 4. The data is ; delimited and you have &amp; in one of the fields. Since there is a delimiter there, it's being parsed as the end of the field. For that to be valid, you need to escape the field with quotes.

This is what that should look like if it's valid.

Title;Description;Count
Title 123;"do &amp; don't";3
vinaypatelce commented 9 years ago

Hello Josh,

Thanks for your reply.

TRecord is generic type that i pass in my method in which this code belong.

I dot'n have control on csv data, I'm reading third party data so i cant put quotes.

How can i solve it?

JoshClose commented 9 years ago

There really is nothing to do but sanitize the data before you run it through CsvHelper. The only way to tell is by a human eye looking at it. CSV data should be following RFC 4180 https://tools.ietf.org/html/rfc4180

vinaypatelce commented 9 years ago

Thank you Josh for your time and help.

Oxymoron290 commented 9 years ago

Wouldn't the quotes around do &amp; don't make the semicolon in the middle ignored?

JoshClose commented 9 years ago

If you put quotes around a field, everything in the field is text of that field. It's not ignored, but not treated as a delimiter.