hasib budi

hasib budi

  • 2.1k
  • 20
  • 3k

loop through csv file

Sep 22 2020 3:38 AM
Have a proble with loop through csv file. Example i have two csv file in folder. csvfile1 has 10 row, and csvfile2 has 20 row. It will insert into database. And if a 2 new row added in csvfile1, Only insert into database those 2 new row.
  1. foreach(string path in Directory.EnumerateFiles(@"C:\ihelp\record""*.csv")) {  
  2.   string[] lines = File.ReadAllLines(path);  
  3.   List < string > list = new List < string > (lines);  
  4.   list.RemoveAt(0);  
  5.   list.RemoveAt(0);  
  6.   list.RemoveAt(0);  
  7.   int row = list.Count;  
  8.   Console.WriteLine("CSV got : " + row + " line");  
  9.   var upd1 = "update list set lastrow =@lastrow where filename =@filename";  
  10.   var cmd5 = new NpgsqlCommand(upd1, conn);  
  11.   cmd5.Parameters.AddWithValue("@filename", Convert.ToString(path));  
  12.   cmd5.Parameters.AddWithValue("@lastrow", Convert.ToDouble(row));  
  13.   cmd5.ExecuteNonQuery();  
  14.   if (row >= RecordCount) {  
  15.     for (int f = RecordCount; f < row; f++) {  
  16.       var line = list[f];  
  17.       Console.WriteLine("Record count :" + RecordCount);  
  18.       Console.WriteLine("line :" + line);  
  19.       var columns = line.Split(',');  
  20.       var sql = "insert into result(datetime,name)values(@datetime,@name)";  
  21.       var cmd6 = new NpgsqlCommand(sql, conn);  
  22.       for (int i = 0; i < columns.Length; i++) {  
  23.         if (i == 0) {  
  24.           cmd6.Parameters.AddWithValue("datetime", Convert.ToDateTime(columns[i]));  
  25.           string Time = cmd6.Parameters["@datetime"].Value.ToString();  
  26.           Console.WriteLine("Record inserted successfully. datetime = " + columns[i]);  
  27.         }  
  28.         if (i == 1) {  
  29.           cmd6.Parameters.AddWithValue("name", Convert.ToString(columns[i]));  
  30.           string name = cmd6.Parameters["@name"].Value.ToString();  
  31.           Console.WriteLine("Record inserted successfully. name = " + columns[i]);  
  32.         }  
  33.       }  
  34.     }  
  35.     cmd6.ExecuteNonQuery();  

Answers (2)