c# - Don't split the string if contains in double marks -
i have text delimeted file need convert datatable. given text :
name,contact,email,date of birth,address john,01212121,hehe@yahoo.com,1/12/1987,"mawar rd, shah alam, selangor" jackson,01223323,haha@yahoo.com,1/4/1967,"neelofa rd, sepang, selangor" david,0151212,hoho@yahoo.com,3/5/1956,"nora danish rd, klang, selangor"
and how read text file in c#
datatable table = new datatable(); using (streamreader sr = new streamreader(path)) { #region text csv while (!sr.endofstream) { string[] line = sr.readline().split(','); //table.rows.add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]); if (isrowheader)//is user want read first row header { foreach (string column in line) { table.columns.add(column); } totalcolumn = line.count(); isrowheader = false; } else { if (totalcolumn == 0) { totalcolumn = line.count(); (int j = 0; j < totalcolumn; j++) { table.columns.add(); } } // create datarow using .newrow() datarow row = table.newrow(); // iterate on columns fill row (int = 0; < line.count(); i++) { row[i] = line[i]; } // add current row datatable table.rows.add(row); } }
the column dynamic, user can add or remove column on text file. need check how many column , set datatable, after read each line, set value datarow , add row table.
if don't remove semicolon inside double marks, show error "cannot find column 5" because on first line 4 column (start 0).
what best way deal text delimited?
don't try , re-invent csv-parsing wheel. use parser built .net: microsoft.visualbasic.fileio.textfieldparser
Comments
Post a Comment