0

I have some csv data:

"data1", "data2", "data2_1", "data3"

I am using csvHelper to read the data.

When I read the data and split it using separator ',' I am getting 4 records.

"data1", 
"data2", 
"data2_1", 
"data3"

But I want 3 records as I have 3 columns

"data1", 
"data2, data2_1", 
"data3"

Below is code I am trying

var config = new CsvConfiguration() { HasHeaderRecord = false };
var stream = File.OpenRead(FilePath);
using (var csvReader = new CsvReader(new StreamReader(stream, Encoding.UTF8), config))
    {
        while (csvReader.Read()) {
        var parser = csvReader.Parser;
        var rowRecors = parser.RawRecord;
        var splitedData = rowRecors.Split(',');
    }
Rob Quincey
  • 2,834
  • 2
  • 38
  • 54
Hemant Malpote
  • 891
  • 13
  • 28
  • I would look for some method on `CvsReader` and its ilk to do the splitting, that's what it's for. If you do the split yourself, why are you even bothering using a tool? – oerkelens Dec 20 '17 at 08:52
  • Can you point us to the exact csv helper library you are using (a link)? CsvReader is a lot generic – Steve Dec 20 '17 at 08:56
  • Possible duplicate of [Dealing with commas in a CSV file](https://stackoverflow.com/questions/769621/dealing-with-commas-in-a-csv-file) – Sentry Dec 20 '17 at 08:56
  • I don't find any splitting in csvReader. If i get it from csvReadrer its fine for me – Hemant Malpote Dec 20 '17 at 08:56

2 Answers2

1

It seems that you are using this library: CsvHelper

Your file data is quoted meaninig that each field is enclosed in double quotes for the exact reason that some fields can contain the field separator (the comma). In this case you should inform your library what is the character used to quote your fields so it can ignore the presence of the field separator when it is inside the quotes pair.

This library offers the Configuration class that you already initialize.
You just need to add this to the constructor

var config = new CsvConfiguration() 
                 { 
                     HasHeaderRecord = false,
                     Quote = '"'
                 };

See the properties list at CsvHelper.Configuration

Steve
  • 213,761
  • 22
  • 232
  • 286
0

Don't split manually and instead use lib functions

    // By header name
var field = csv["HeaderName"];

    // Gets field by position returning string
var field = csv.GetField( 0 );



 // Gets field by position returning int
    var field = csv.GetField<int>( 0 );

// Gets field by header name returning bool
var field = csv.GetField<bool>( "IsTrue" );

// Gets field by header name returning object
var field = csv.GetField( typeof( bool ), "IsTrue" );

Refer reading samples

gramcha
  • 692
  • 9
  • 16