0

Follow up from my previous question: Previous Question Here

I have now got the service to monitor the folder and insert data into the intended table, however, it is inserting the data between 1-4 times.

The code can be seen below for my service class:`using System;

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);
                }
            }
        }
    }
}

First time looking at FileSystemWatchers and there's nothing really online which is similar to my exact scenario (with the database insert), therefore, any help will be greatly appreciated!

Kind Regards

Edit: I've tried 6-7 of the fixes on the question being flagged as a duplicate and none of them have worked.

Adam
  • 62
  • 6
  • 1
    You are doing 2 things here, why don't you forget about the database, and test this with just the debug.window in a console app and reduce the degrees of freedom, then you can work out if its the db, or the that you dont understand what the FSW is doing, which in turn will make your question more specific – TheGeneral Feb 27 '19 at 10:00
  • What program writes the data in the observed directories? How often does this program open and close the file writing to? – nabuchodonossor Feb 27 '19 at 10:00
  • @MichaelRandall I've ran the database part by itself in a console application, worked fine - inserted one line. Looks to be with the FSW, running the 'FileSystemWatcher_Changed' Method multiple times – Adam Feb 27 '19 at 10:02
  • Could it be the file is getting updated multiple times? – TheGeneral Feb 27 '19 at 10:03
  • @nabuchodonossor At the moment I'm manually copying a file over to the test folder. The folder will act as a dump folder for scanning in a live scenario – Adam Feb 27 '19 at 10:04
  • @MichaelRandall i'm copying a file over to the folder which is not being changed/renamed/edited once in the folder. The insert happens on create, and I have commented out the change eventhandler because I thought this was the case too – Adam Feb 27 '19 at 10:15
  • Possible duplicate of [FileSystemWatcher Changed event is raised twice](https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice) – nabuchodonossor Feb 27 '19 at 10:46
  • @nabuchodonossor That question was asked 10 years ago and doesn't have a chosen answer. I've tried 4 of the suggestions, no luck whatsoever. Could be because I do not know how to adapt the suggestions to my code as this is all very new to me. – Adam Feb 27 '19 at 11:58
  • @Adam: Then the next step would be: Try the idea of Michael (write only small programm only for logging the filewatcher events to see, if the copy file triggers multiple times. – nabuchodonossor Feb 27 '19 at 12:12
  • @Adam: And one guy wrote a class solving the troubles -> free to download. Take a second look at the referenced post. – nabuchodonossor Feb 27 '19 at 12:22
  • @nabuchodonossor are you referring to the FileSystemSafeWatcher class? If so, this does not handle Microsoft Office documents correctly and this will be the most common document types being uploaded into the directory – Adam Feb 27 '19 at 13:32
  • @Adam: Please define "not correctly". If a file is copied, it is copied, and this is triggered multiple times (as far as I understand your task). This should not make a difference of what filetype this is. – nabuchodonossor Feb 27 '19 at 14:13

0 Answers0