0

Possible Duplicate:
Reading csv file

I have a comma delimited file:

"Some Text, More Text", 1, 2, 3,4,5,6
"Random Text, text text", 2,4,5,6,7,8
var content = reader.ReadLine();
var stringArray = content.Split(',');

The problem is the text ends up being split into two parts. I want to keep it as one unit. So what are my options?

EDIT: I meant like

Some Text

More Text 1

2

3

4

5

6

I want it like

Some Text,More Text

1

2

3

4

5

6

Community
  • 1
  • 1
Mike Diaz
  • 2,045
  • 4
  • 32
  • 55
  • 1
    (Without being too much of a smarty-wishbone-legs) Please google "C# CSV Reader"... I just did, and theres quite a selection of free ones on offer... including several generations of preceeding questions asked and answered (well) on stack overflow itself. Sigh. http://stackoverflow.com/questions/906841/csv-parser-reader-for-c – corlettk Jun 04 '11 at 23:45

3 Answers3

1

How about finding all the matches of this regex:

"[^"]*"|\S+
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
  • +1 Nice and simple, and good for 99% of (valid) CSV formats you're likely to encounter in the wild. – corlettk Jun 04 '11 at 23:50
0

I usually use the Microsoft.VisualBasic.FileIO.TextFieldParser object, see:

http://msdn.microsoft.com/en-us/library/f68t4563.aspx

and example of implementation at:

http://www.siccolo.com/Articles/CodeProject/Open_DataSet_From_TextFile/open_dataset_from_text_csv_file.html

This allows me to handle CSV files without worrying about how to cope with whether fields are enclosed in quotes, contain commas, escaped quotes etc.

Graham
  • 14,885
  • 4
  • 36
  • 42
-1

You need to use Regex in Split, so that text in quotes are excluded!

Akhil
  • 7,570
  • 1
  • 24
  • 23
  • This would be more appropriate as a comment. – icktoofay Jun 04 '11 at 23:48
  • ok, got it. You need to use Regex in Split, so that text in quotes are excluded! – Akhil Jun 04 '11 at 23:48
  • Dude, for your future reference: Requests for clarification of the question are best posted as Comments on the question (not answers, which they aren't). – corlettk Jun 04 '11 at 23:48
  • ok dude. point noted. my 2nd comment is not a clarification. its an answer to the question. if you think it doesnt help, let me know, n i will delete the whole answer. – Akhil Jun 04 '11 at 23:49
  • Edit your answer and move the answer into the answer where it belongs. – icktoofay Jun 05 '11 at 00:01