/// <summary> /// convert csv to data table /// </summary> /// <param name="fileSaveWithPath"></param> /// <returns></returns> public DataTable ReadCsvFile(string fileSaveWithPath) { DataTable dtCsv = new DataTable(); string Fulltext; try { if (!String.IsNullOrEmpty(fileSaveWithPath)) { using (StreamReader sr = new StreamReader(fileSaveWithPath)) { while (!sr.EndOfStream) { Fulltext = sr.ReadToEnd().ToString(); //read full file text Fulltext = Fulltext.Replace("\r", ""); string[] rows = Fulltext.Split('\n'); //split full file text into rows for (int i = 0; i < rows.Count() - 1; i++) { string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values { if (i == 0) { for (int j = 0; j < rowValues.Count(); j++) { dtCsv.Columns.Add(rowValues[j]); //add headers } } else { DataRow dr = dtCsv.NewRow(); for (int k = 0; k < dtCsv.Columns.Count; k++) { dr[k] = rowValues[k].ToString(); } dtCsv.Rows.Add(dr); //add other rows } } } } } } } catch (Exception e) { throw new InvalidDataException("CSVFile content is not correct "); } return(dtCsv); }
private static DataTable GetDatasetFromCsv(string csvFileName) { DataTable dtCsv = new DataTable(); string Fulltext; var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); string FileSaveWithPath = path.Replace(@"file:\", "") + @"\Datasets\" + csvFileName; using (StreamReader sr = new StreamReader(FileSaveWithPath)) { while (!sr.EndOfStream) { Fulltext = sr.ReadToEnd().ToString(); //read full file text Fulltext = Fulltext.Replace("\r", ""); string[] rows = Fulltext.Split('\n'); //split full file text into rows for (int i = 0; i < rows.Count() - 1; i++) { string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values { if (i == 0) { for (int j = 0; j < rowValues.Count(); j++) { dtCsv.Columns.Add(rowValues[j]); //add headers } } else { DataRow dr = dtCsv.NewRow(); for (int k = 0; k < rowValues.Count(); k++) { dr[k] = rowValues[k].ToString(); } dtCsv.Rows.Add(dr); //add other rows } } } } } return(dtCsv); }