Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net Convert CSV string to string[]

Tags:

string

c#

csv

Is there an easy way to convert a string from csv format into a string[] or list?

I can guarantee that there are no commas in the data.

like image 636
Col Avatar asked Sep 16 '08 15:09

Col


4 Answers

String.Split is just not going to cut it, but a Regex.Split may - Try this one:

using System.Text.RegularExpressions;

string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

Where 'input' is the csv line. This will handle quoted delimiters, and should give you back an array of strings representing each field in the line.

like image 128
Philip Rieck Avatar answered Sep 22 '22 13:09

Philip Rieck


If you want robust CSV handling, check out FileHelpers

like image 38
John Sheehan Avatar answered Sep 22 '22 13:09

John Sheehan


string[] splitString = origString.Split(',');

(Following comment not added by original answerer) Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.

like image 30
Timothy Carter Avatar answered Sep 21 '22 13:09

Timothy Carter


Try:

Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );

Source: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx

like image 34
Panos Avatar answered Sep 21 '22 13:09

Panos