Search code examples
c#windowsservicefilesystemwatcher

Windows service with FileSystemWatcher event does not trigger


I am trying to create a Windows Service that would run all the time to check with a FileSystemWatcher if files are added to a folder. I succeed to run a Windows Service alone and a FileSystemWatcher alone too but i can't get those applications to work together. I am not sure what i am doing wrong and i am a beginner with C#.

Here is what i wrote :

Service class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace WinServiceProject
{
    using System;
    using System.IO;

    class WinService2 : System.ServiceProcess.ServiceBase
    {
        private static string folderPath = @"c:\temp";
        private Watcher wat;

        static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun =
              new System.ServiceProcess.ServiceBase[] { new WinService2() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }

        private void InitializeComponent()
        {
            this.ServiceName = "WinService";
        }

        protected override void OnStart(string[] args)
        {
            wat = new Watcher();
            if (!System.IO.Directory.Exists(folderPath))
                System.IO.Directory.CreateDirectory(folderPath);

            FileStream fs = new FileStream(folderPath + "\\WindowsService.txt",
                                FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" WindowsService: Service Started at " +
               DateTime.Now.ToShortDateString() + " " +
               DateTime.Now.ToShortTimeString() + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

        protected override void OnStop()
        {
            FileStream fs = new FileStream(folderPath +
              "\\WindowsService.txt",
              FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" WindowsService: Service Stopped at " +
              DateTime.Now.ToShortDateString() + " " +
              DateTime.Now.ToShortTimeString() + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }
    }
}

FileSystemWatcher class :

using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public static void Run()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\Users\Accueil\Downloads\Téléchargements\test";
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.txt";

        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);

        watcher.EnableRaisingEvents = true;
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        FileStream fs = new FileStream(@"C:\temp\WindowsService3.txt",
                                FileMode.OpenOrCreate);
    }
}

ServiceInstaller class :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinServiceProject
{
    using System;

    [System.ComponentModel.RunInstaller(true)]
    public class ProjectInstaller : System.Configuration.Install.Installer
    {
        private System.ServiceProcess.ServiceInstaller serviceInstaller;
        private System.ServiceProcess.ServiceProcessInstaller
                serviceProcessInstaller;

        public ProjectInstaller()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.serviceInstaller = new System.ServiceProcess.ServiceInstaller();
            this.serviceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();

            this.serviceInstaller.Description = "My Windows Service description";
            this.serviceInstaller.DisplayName = "My WinService";
            this.serviceInstaller.ServiceName = "WinService";

            this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
            this.serviceProcessInstaller.Password = null;
            this.serviceProcessInstaller.Username = null;

            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller,
            this.serviceInstaller});
        }
    }
}

Solution

  • SOLUTION :

    Modifying the Service class by calling Watcher.Run(); in the OnStart method:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Configuration;
    
    namespace WinServiceProject
    {
        using System;
        using System.IO;
    
        class WinService2 : System.ServiceProcess.ServiceBase
        {
            private static string folderPath = @"c:\temp";
    
            static void Main()
            {
                System.ServiceProcess.ServiceBase[] ServicesToRun;
                ServicesToRun =
                  new System.ServiceProcess.ServiceBase[] { new WinService2() };
                System.ServiceProcess.ServiceBase.Run(ServicesToRun);
            }
    
            private void InitializeComponent()
            {
                this.ServiceName = "WinService";
            }
    
            protected override void OnStart(string[] args)
            {
                Watcher.Run();
                if (!System.IO.Directory.Exists(folderPath))
                    System.IO.Directory.CreateDirectory(folderPath);
    
                FileStream fs = new FileStream(folderPath + "\\WindowsService.txt",
                                    FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(" WindowsService: Service Started at " +
                   DateTime.Now.ToShortDateString() + " " +
                   DateTime.Now.ToShortTimeString() + "\n");
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
    
            protected override void OnStop()
            {
                FileStream fs = new FileStream(folderPath +
                  "\\WindowsService.txt",
                  FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(" WindowsService: Service Stopped at " +
                  DateTime.Now.ToShortDateString() + " " +
                  DateTime.Now.ToShortTimeString() + "\n");
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
        }
    }