c# - Storing a DataTable in a Flatfile -
this first time have done sort of work flat files. need plain txt file not xml.
i have written following opting comma delimited format.
public static void datatabletofile(string fileloc, datatable dt) { stringbuilder str = new stringbuilder(); // column headers foreach (datacolumn c in dt.columns) { str.append(c.columnname.tostring() + ","); } str.remove(str.length-1, 1); str.appendline(); // write data here foreach (datarow dr in dt.rows) { foreach (var field in dr.itemarray) { str.append(field.tostring() + ","); } str.remove(str.length-1, 1); str.appendline(); } try { write(fileloc, str.tostring()); } catch (exception ex) { //todo:add error logging } } my question is: can better or faster? , str.remove(str.length-1, 1); there remove last , way think of. suggestions?
use
public static void datatabletofile(string fileloc, datatable dt) { stringbuilder str = new stringbuilder(); // column headers str.append(string.join(",", dt.columns.cast<datacolumn>() .select(col => col.columnname)) + "\r\n"); // write data here dt.rows.cast<datarow>().tolist() .foreach(row => str.append(string.join(",", row.itemarray) + "\r\n")); try { write(fileloc, str.tostring()); } catch (exception ex) { //todo:add error logging } }
Comments
Post a Comment