Am trying to read this csv file that I will later choose the distinct elements in it and create a truth table if each element exists in a row I put 1 If not 0 The line/row length keeps isn't constant and that's what am having trouble with
chicken,other vegetables,packaged fruit/vegetables,condensed milk,frozen vegetables,fruit/vegetable juice
vinegar,oil
rolls/buns,soda,specialty bar
whole milk
pork,root vegetables,whole milk,whipped/sour cream
rolls/buns,newspapers
grapes,other vegetables,zwieback,Instant food products,dishes
frankfurter,citrus fruit,whipped/sour cream,cream cheese ,rolls/buns,baking powder,seasonal products,napkins
finished products,root vegetables,packaged fruit/vegetables,yogurt,specialty cheese,frozen vegetables,ice cream,soda,bottled beer
onions,other vegetables,flour
tropical fruit,whole milk,rolls/buns
Am using this following code
static void Main(string[] args)
{
string filepath = @"C:\Downloads\groceriess.csv";
DataTable res = ConvertCSVtoDataTable(filepath);
DataTable ConvertCSVtoDataTable(string strFilePath)
{
StreamReader sr = new StreamReader(strFilePath);
string[] headers = sr.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{ //i did try i<rows.Length and also i < headers.Length && i <rows.Length
dr[i] = rows[i]; //this is the line that is causing the error
}
dt.Rows.Add(dr);
}
return dt;
}
}