Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I want read words in a text file of a line separated by commas in c# but have a problem with one column is Address and have comma the split method also removes comma from address field.For example Having tree column Name Dept Address with abc,hgd, 12K,Ram Nagar; i don't want remove comma from address field.

Please help me.

What I have tried:

string[] lines = File.ReadAllLines( filename );
foreach ( string line in lines )
{
string[] col = line.Split( new char[] {','} );

}
Posted
Updated 28-Dec-16 22:12pm
v2
Comments
Maciej Los 28-Dec-16 9:10am    
Comma, where? You use semicolon to split data, not a comma!
maneeshsingh07 29-Dec-16 4:21am    
My fault, now i have updated please help now.
[no name] 28-Dec-16 20:00pm    
Some background reading is in order: Comma-separated values - Wikipedia[^]

0) If the address field doesn't have quotes around it, there's really no way you can expect to be able to accurately parse the string.

1) If you're parsing a CSV file that came from Excel, there are a number of CSV file parsers available, including this one, right here on CodeProject: CSV File Parser[^]
 
Share this answer
 
Comments
maneeshsingh07 28-Dec-16 8:12am    
Sir if quotes around this field then..
Jon McKee 28-Dec-16 21:20pm    
Parse on ". Assuming address isn't the first field and is the only field that contains your delimiter it will be the 2nd token. Then parse tokens 1 and 3 as necessary. Could also use regular expression balancing groups but that's a headache if you aren't absolutely certain of the format which you seem to not be.

Another option is to simply use a delimiter that isn't a symbol that appears in your data like Hin Wai suggested below.
#realJSOP 29-Dec-16 9:45am    
You're either gonna have to use a CSV parser like the one cited in my answer, or you're gonna have to write more code. Doing a simple split won't help you. You haven't really provided enough info to allow anyone to help you.
Well, due to the code you'd posted, i do not believe that address is splitted into parts, because you're using a [;] (semicolon) as a divisor.
C#
string[] lines = File.ReadAllLines( filename );
foreach ( string line in lines )
{
 string[] col = line.Split( new char[] {';'} );
} 

[OP has changed the question ]

Please, read my past answer[^] to find out that you need ADO.NET (OleDb) to resolve your issue.
 
Share this answer
 
v2
use a different deliminator instead of ","
 
Share this answer
 
Comments
Maciej Los 29-Dec-16 2:09am    
OP is using a ';' (semicolon).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900