c# - How to split csv whose columns may contain , -


given

2,1016,7/31/2008 14:22,geoff dalgas,6/5/2011 22:21,http://stackoverflow.com,"corvallis, or",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34

how use c# split above information strings follows:

2 1016 7/31/2008 14:22 geoff dalgas 6/5/2011 22:21 http://stackoverflow.com corvallis, or 7679 351 81 b437f461b3fd27387c5d8ab47a293d35 34 

as can see 1 of column contains , <= (corvallis, or)

// update // based on c# regex split - commas outside quotes

string[] result = regex.split(samplestring, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); 

use microsoft.visualbasic.fileio.textfieldparser class. handle parsing delimited file, textreader or stream fields enclosed in quotes , not.

for example:

using microsoft.visualbasic.fileio;  string csv = "2,1016,7/31/2008 14:22,geoff dalgas,6/5/2011 22:21,http://stackoverflow.com,\"corvallis, or\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";  textfieldparser parser = new textfieldparser(new stringreader(csv));  // can read file // textfieldparser parser = new textfieldparser("mycsvfile.csv");  parser.hasfieldsenclosedinquotes = true; parser.setdelimiters(",");  string[] fields;  while (!parser.endofdata) {     fields = parser.readfields();     foreach (string field in fields)     {         console.writeline(field);     } }   parser.close(); 

this should result in following output:

 2 1016 7/31/2008 14:22 geoff dalgas 6/5/2011 22:21 http://stackoverflow.com corvallis, or 7679 351 81 b437f461b3fd27387c5d8ab47a293d35 34 

see microsoft.visualbasic.fileio.textfieldparser more information.

you need add reference microsoft.visualbasic in add references .net tab.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -