简体   繁体   中英

C# FileSystemWatcher Windows service does not start

I have created and installed C# FileSystemWatcher , this part works but nothing happens when I add a file to the source folder, the file I add to the source folder should be copied to a destination folder, but that does not happen.

This is my Filesyswatcher.designer.cs

using System;
using System.Configuration;
using System.IO;

namespace HotFolderWatch
{
    partial class FileSysWatcher
    {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.FSWatcher = new System.IO.FileSystemWatcher();
            ((System.ComponentModel.ISupportInitialize)(this.FSWatcher)).BeginInit();
            // 
            // FSWatcher
            // 


            this.FSWatcher.Changed += new FileSystemEventHandler(FSWatcher_Changed);
            this.FSWatcher.Created += new FileSystemEventHandler(FSWatcher_Created);
            this.FSWatcher.Deleted += new FileSystemEventHandler(FSWatcher_Deleted);

            this.FSWatcher.EnableRaisingEvents = true;

            this.FSWatcher.NotifyFilter = ((System.IO.NotifyFilters)((((((System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName) 
            | System.IO.NotifyFilters.Size) 
            | System.IO.NotifyFilters.LastWrite) 
            | System.IO.NotifyFilters.LastAccess) 
            | System.IO.NotifyFilters.CreationTime)));
            // 
            // FileSysWatcher
            // 
            this.ServiceName = "FileSysWatcher";
            ((System.ComponentModel.ISupportInitialize)(this.FSWatcher)).EndInit();

        }

        #endregion

        private System.IO.FileSystemWatcher FSWatcher;


        /* DEFINE WATCHER EVENTS... */
        /// <summary>
        /// Event occurs when the contents of a File or Directory are changed
        /// </summary>
        private void FSWatcher_Changed(object sender,
                    System.IO.FileSystemEventArgs e)
        {
            //code here for newly changed file or directory
        }
        /// <summary>
        /// Event occurs when the a File or Directory is created
        /// </summary>
        private void FSWatcher_Created(object sender,
                        System.IO.FileSystemEventArgs e)
        {
            //code here for newly created file or directory
            try
            {
                System.IO.File.Copy(e.FullPath, DestinationPath + e.Name, true);
            }
            catch (Exception ex)
            {
                //Util.WriteToErrorLogFile(ex);
            }


        }
        /// <summary>
        /// Event occurs when the a File or Directory is deleted
        /// </summary>
        private void FSWatcher_Deleted(object sender,
                        System.IO.FileSystemEventArgs e)
        {
            //code here for newly deleted file or directory
        }


    }
}

And this is my FileSysWatcher.cs file..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace HotFolderWatch
{
    partial class FileSysWatcher : ServiceBase
    {
        private string _userName;

        public FileSysWatcher()
        {
            InitializeComponent();
        }

        public static string DestinationPath;

        public const string MyServiceName = "FileSysWatcher";
        private FileSystemWatcher watcher = null;


        protected override void OnStart(string[] args)
        {
            FSWatcher.Path = ConfigurationManager.AppSettings["WatchPath"];
            DestinationPath = ConfigurationManager.AppSettings["DestinationPath"];

            _userName = Environment.UserName;


            // Begin watching.
            FSWatcher.EnableRaisingEvents = true;

        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }
    }
}

I have also tried to attach to the process while debugging but the event does not seem to occur, anyone see any mistakes that could cause this?

I have tested your code on my system (Windows 7 64): it works. A few things you should check:

  • Is the WatchPath / DestinationPath a local path on the system where the service is running ? Be aware that accessing a network share by a service typically requires that the service runs under a (domain) user account. Also, a mapped network drive is not seen by the service, so you should use UNC paths if acessing (SMB) file shares.
  • At the moment where the created event triggers, the file could be in use, so your copy may fail.

and the logging is commented beacuse that part isnt executed either.

Ok, but nevertheless, you should add more logging.

My Windows services usually contain:

protected override void OnStart(string[] args)
{
    // this is not just a simple message, this has to be called very early before any worker thread
    // to prevent a race condition in the .NET code of registering the event source
    EventLog.WriteEntry("XxxxService is starting", EventLogEntryType.Information, 1000);

I was recently faced this issue, found this code below in above answer,

FSWatcher.EnableRaisingEvents = true;

This line of code was throwing exception previously, but later on, after adding above line, my watcher was triggering events, which makes no sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM