Muhamad Fahmi

Muhamad Fahmi

  • 1.9k
  • 44
  • 813

check file exist in database

Aug 23 2020 10:13 PM
Hi, have a problem with code below. Code below is to check if the csv file name is already save in database or if not,i will go insert. But when i run the code it will keep doing insert statement.
Help me
 
foreach (FileInfo file in filess)
                {
                    DateTime lastWriteTime = file.LastWriteTime;

                    Console.WriteLine("File list : " + file);
                    Console.WriteLine("Time last Edit : " + lastWriteTime);

                    var sel = "select * from listfile where filename=@filename";
                    var cmd2 = new NpgsqlCommand(sel, conn);
                    DataTable dt = new DataTable();
                    conn.Open();

                    cmd2.Parameters.AddWithValue("filename", Convert.ToString(file));
                    cmd2.ExecuteNonQuery();
                    conn.Close();

                    if (dt.Rows.Count >= 1)
                    {
                        Console.WriteLine("File exist in database.");
                    }
                    else
                    {
                        var lf = "insert into listfile(filename)values(@filename)";
                        var cmd = new NpgsqlCommand(lf, conn);
                        conn.Open();

                        cmd.Parameters.AddWithValue("filename", Convert.ToString(file));
                        string filename1 = cmd.Parameters["@filename"].Value.ToString();
                        Console.WriteLine("Record inserted successfully. filename = " + file);

                        cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }

Brought to you by:

Answers (8)