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.