C# - 如何将代码安排到每天的特定时间 运行 并仅在数据库 table 中添加该行时才发送电子邮件

C# - how do I schedule code to run everyday on a specific time and send email only when the row is added in a database table

我写的现在有一个代码可以将 SFTP 站点中的文件更新并列出到数据库中 table。每当有新文件上传到客户端 SFTP 站点时,我应该会收到一封电子邮件通知。为此,我在本地机器上设置了一个任务调度程序。现在,我每天都会在设定的时间收到一封电子邮件,这很好,但是我如何才能只在 sftp 站点上传新文件或将新的 row/s 添加到数据库中时才收到电子邮件table。我不想每天都收到邮件,只有当有新文件时邮件通知我。

请指出正确的方向。我该怎么办?

    public static void Main()
    {
        string host = @"";
        string username = "";
        string password = @"";
     

        Dictionary<string, string[]> fileMetadata = new Dictionary<string, string[]>();


        using (SftpClient sftp = new SftpClient(host, username, password))
        {
            List<DateTime> sftpdates = new List<DateTime>();
            IEnumerable<SftpFile> files = null;
            try
            {
                sftp.Connect();
                files = sftp.ListDirectory(".");

                // Get SFTP dates 

                foreach (var file in files)

                {
                    Console.Write(file.Name + "\t");
                    Console.WriteLine(file.Attributes.LastWriteTime);
                    if (!file.Name.Equals(".") || !file.Name.Equals(".."))
                    {

                    }
                    sftpdates.Add(file.Attributes.LastWriteTime);
                }
                sftp.Disconnect();
                sftpdates.Sort();
                sftpdates.Reverse();
                Console.WriteLine("Latest " + sftpdates[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine("An exception has been caught " + e.ToString());
            }


            // get lastestfile recieved stored in a DB and Compare the dates ( greater or not ) if yes ;
            var con = new SqlConnection(@"connection string here");
            con.Open();
            {
                SqlCommand getMaxdateDB = new SqlCommand
               ("select * from LatestFile ", con);
                SqlDataReader reader = getMaxdateDB.ExecuteReader();
                DateTime DatabaseDate = new DateTime();
                while (reader.Read())
                {
                    DatabaseDate = reader.GetDateTime(0);
                }
                reader.Close();

                if (sftpdates[0].CompareTo(DatabaseDate) > 0)
                {
                    Console.WriteLine("Newer file exists");
                }
                else if (sftpdates[0].CompareTo(DatabaseDate) == 0)

                {
                    Console.WriteLine("Latest dates are same");
                }
            }

            // if yes // send new records to db 
            {
                foreach (var file in files)
                {
                    SqlCommand getFile = new SqlCommand(
                            "select FILE_NAME, date_modified from NewFileUpload where File_Name='"
                            + file.Name + "';", con);
                    SqlDataReader readfile = getFile.ExecuteReader();
                    bool row = readfile.HasRows;
                    string fileName;
                    DateTime date_modified = new DateTime();
                    try
                    {
                        fileName = readfile.GetString(0);
                        date_modified = readfile.GetDateTime(1);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                    readfile.Close();
                    if (row == false)
                    {
                        Console.WriteLine("New file added...");
                        DateTime myDateTime = file.Attributes.LastWriteTime;
                        string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        SqlCommand cm = new SqlCommand("insert into NewFileUpload(File_Name, File_Size, Date_Modified) values " +
                    "('" + file.Name + "', '" + file.Attributes.Size + "', '" + sqlFormattedDate + "')", con);
                        cm.ExecuteNonQuery();
                        fileMetadata.Add(file.Name, new string[] { file.Attributes.Size.ToString(), sqlFormattedDate });

                    }
                }
                // send email
                // EMAIL LOGIC
                SendEmailMultiFiles(fileMetadata);

                {
                    SqlCommand UpdateLatestDate = new SqlCommand
                        ("truncate table LatestFile", con);
                    UpdateLatestDate.ExecuteNonQuery();
                    UpdateLatestDate = new SqlCommand
                   ("INSERT INTO LatestFile select max(Date_Modified) from NewFileUpload where File_Name not in ('..' ,'.')", con);
                    UpdateLatestDate.ExecuteNonQuery()


                }
            }


        }
        Console.ReadKey();
    }

    static void SendEmail(string filename, long filesize, DateTime datemodified)


    {

        //List <> NewUploadList = List  <> NewUploadList = new List<>(); /// might only send the date or file name
        // Key = filename
        // value = [filesize(string), datemodified/lastwrite(string)]
        Dictionary<string, string[]> fileMetadata = new Dictionary<string, string[]>();
    }

    static void SendEmailMultiFiles(Dictionary<string, string[]> fileMetadata
   

        //List <> NewUploadList = List  <> NewUploadList = new List<>(); /// might only send the date or file name
        Console.WriteLine("Email has been sent.");
        string SendMailbody = "File(s) added<br>";
        //+ filename + " file size: "
        //+ filesize + " date modified: "
        //+ datemodified;
        int i = 1;
        foreach (var item in fileMetadata)
        {
            SendMailbody += i++ + ") " + item.Key + " file size: "
                + item.Value[0] + " date modified: "
                + item.Value[1] + "<br>";
        }

        string mailto = "";
        string mailfrom = "";

        MailMessage mail = new MailMessage();
        mail.From = new System.Net.Mail.MailAddress(mailfrom);

        SmtpClient smtp = new SmtpClient();
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential("", "");
        smtp.Host = "smtp.gmail.com";
     
        mail.Subject = "New File Incoming";
        mail.IsBodyHtml = true;
        mail.Body = SendMailbody;
        smtp.Send(mail);



    }
}

}

只需在发送到函数之前检查 fileMetadata 对象。

If (fileMetadata.Count >= 1)
{
    SendEmailMultiFiles(fileMetadata);
}