Chethan
Chethan

Reputation: 300

CSV file parsing issue

I am trying to read CSV file, and i am success to some extent.

i tried

string[] values = strCurLine.Split(',');

and i am getting output as

array[0]="180"  
array[1]="LMN"  
array[2]="8"  
array[3]="5/17/2012 15:00"  
array[4]=""  
array[5]="name"  
array[6]="2nd row"  
array[7]="step 2 from 4 to 2"  
array[8]="7/9/2012  8:47:00 AM"  

But when i am trying to read a content which contains , (comma) in it, its giving additional array item, and because of this i am loosing data. how can i replace a comma(,) in string.

My expected output is

array[0]="180"  
array[1]="LMN"  
array[2]="8"  
array[3]="5/17/2012 15:00"  
array[4]=""  
array[5]="name"  
array[6]="2nd row, step 2 from 4 to 2"  
array[7]="7/9/2012  8:47:00 AM"  

Please suggest

Upvotes: 1

Views: 63

Answers (2)

Chethan
Chethan

Reputation: 300

Check here, i got answer to my question

Dealing with commas in a CSV file answered by harpo

thanks, happy coding.

Upvotes: 0

Haedrian
Haedrian

Reputation: 4328

You've hit on what is known as a "Delimiter collision"

You're going to need to change either the delimiter itself, or places where you want to put in a comma.

To replace parts of a string you can use String.Replace() - but that won't really help you in this case because it'll break your csv file.

So what I suggest is the following:

Use a different csv delimiter in the file (even though its called csv, you can delimit them with tabs or semicolons) - something you're not expecting to be in the data. If you have complete control of the csv, you could put your own delimiter (maybe ,, or something like that)

or

Put some sort of 'exception' to commas. For instance use \, or ,, to define a comma. Then you can string.replace the entire csv file to a temporary character - and swap it back into a comma after you're done.

Upvotes: 1

Related Questions