KarenDS
KarenDS

Reputation: 41

Ignore Comma between double quotes while reading CSV file

CSV reader made in c# language. It works correctly, but I am not able to ignore a comma(',') between a double quote row value.

Example: "aa", "aa,bb", "cc"

It reads it like

Col1 Col2 Col3 Col4
aa   aa   bb   cc 

and instead of this it should read like,

Col1 Col2 Col3 
aa   aabb cc 

This is my code:

public void LoadFile(String path)
{
    Table.Rows.Clear();
    Table.Columns.Clear();
    StreamReader file = File.OpenText(path);
    String[] header = file.ReadLine().Split(',');
    for (int i = 0; i < Table.ColumnCount; i++)
    {
        Table.Columns[i].Name = "Col " + i;}
        String row = "";
        while ((row = file.ReadLine()) != null)
        {
            Table.Rows.Add(row.Split(','));
        }
        file.Close();
    }
}

Upvotes: 3

Views: 10518

Answers (1)

Leathel
Leathel

Reputation: 385

You can fix this by replacing the Split function with the regex split function

Table.Rows.Add(row.Split(','));

Should be replaced with

Table.Rows.Add(Regex.Split(row, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"));

And add the assembly at the top

using System.Text.RegularExpressions;

This will fix your problem

Upvotes: 14

Related Questions