Windows Service文件监视程序,多次将重复的数据插入数据库

时间:2019-02-27 09:56:28

标签: c# database windows-services filesystemwatcher

跟着我上一个问题:Previous Question Here

我现在获得了监视文件夹并将数据插入到预期表中的服务,但是它正在1-4次之间插入数据。

以下是我的服务类别的代码:

using System.Collections.Generic;  
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;  
using System.IO;  
using System.Linq;  
using System.ServiceProcess;  
using System.Text;  
using System.Threading.Tasks;  
using System.Timers;  
namespace WindowsServiceTest
{
    public partial class Service1 : ServiceBase
    {
        Timer timer = new Timer(); // name space(using System.Timers;)  
        public static string path = ConfigurationManager.AppSettings["findpath"];
        public Service1()
        {
            InitializeComponent();
        } 

        protected override void OnStart(string[] args)
        {
            WriteToFile("Service is started at " + DateTime.Now);
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 5000; //number in milisecinds  
            timer.Enabled = true;
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.NotifyFilter = NotifyFilters.LastWrite;

            //watcher.Created += new FileSystemEventHandler(FileSystemWatcher_Changed);
            watcher.Filter = "*.*";
            watcher.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
            watcher.Changed += new FileSystemEventHandler(FileSystemWatcher_Changed);
            watcher.EnableRaisingEvents = true;
        }

        public static void FileSystemWatcher_Changed(object source, FileSystemEventArgs e)
        {
            using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Database=ServiceTest;Integrated Security=True;"))
            {
                try
                {
                    con.Open();
                    var command = new SqlCommand("Insert into test(URL, Location, Path) values(@URL, @agendaname, @path);", con);
                    command.Parameters.Add("@URL", System.Data.SqlDbType.VarChar, 100).Value = e.Name;
                    command.Parameters.Add("@agendaname", System.Data.SqlDbType.VarChar, 100).Value = ConfigurationManager.AppSettings["agendaname"];
                    command.Parameters.Add("@Path", System.Data.SqlDbType.VarChar, 100).Value = ConfigurationManager.AppSettings["findpath"];
                    command.ExecuteNonQuery();
                    WriteToFile($"Inserted: {e.Name} + {ConfigurationManager.AppSettings["agendaname"]} + {ConfigurationManager.AppSettings["findpath"]}");
                }
                catch(Exception ex)
                {
                    WriteToFile($"{ex}");
                }
                con.Close();
            }
        }
        public static void FileSystemWatcher_Renamed(object source, RenamedEventArgs e)
        {
            WriteToFile($"File Renamed: {e.OldFullPath} renamed to {e.FullPath}");
        }
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            WriteToFile("Service is recalled at " + DateTime.Now);
        }
        protected override void OnStop()
        {

            WriteToFile("Service is stopped at " + DateTime.Now);
        }

        public static void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

第一次查看FileSystemWatchers时,没有什么比我的实际情况(带有数据库插入项)更实际的在线内容,因此,任何帮助将不胜感激!

亲切问候

编辑:我已尝试将问题的6-7修复标记为重复,但没有一个起作用。

0 个答案:

没有答案