C# 不触发具有FileSystemWatcher事件的Windows服务

C# 不触发具有FileSystemWatcher事件的Windows服务,c#,windows,service,filesystemwatcher,C#,Windows,Service,Filesystemwatcher,我正在尝试创建一个Windows服务,该服务将一直运行,以便与FileSystemWatcher检查文件是否添加到文件夹中。我成功地单独运行了Windows服务,也单独运行了FileSystemWatcher,但我无法让这些应用程序协同工作。 我不确定我做错了什么,我是C#的初学者 以下是我写的: 服务类别: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Sy

我正在尝试创建一个Windows服务,该服务将一直运行,以便与FileSystemWatcher检查文件是否添加到文件夹中。我成功地单独运行了Windows服务,也单独运行了FileSystemWatcher,但我无法让这些应用程序协同工作。 我不确定我做错了什么,我是C#的初学者

以下是我写的:

服务类别:

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类:

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);
    }
}
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});
        }
    }
}
ServiceInstaller类:

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

解决方案:

通过调用
Watcher.Run()修改服务类OnStart
方法中的code>:

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

我看不到在哪里调用了
Watcher
Run
方法?还有,你怎么知道它不起作用?您是否在
OnChanged
事件中设置了断点?我看到您创建了watcher而没有运行我不知道初始化一个watch是否会自动执行Run方法,我还尝试在这一行之后调用Run方法:wat=new watcher();但它仍然不起作用。为了知道它是否正常工作,我安装了windows服务,启动了该服务,然后尝试在文件夹中添加一个文件,但如果它正常工作,则应将创建的文件写入文件C:\temp\WindowsService3.txt。我只是在这个文件中有服务的开始时间和停止时间。我希望你们能理解我想说的。把服务的所有逻辑放到不同的类中。然后一步一步地调试这个类。这样,您就不必每次都安装服务,您就有可能调试它。正如前面所说的,似乎必须调用Run方法,所以我替换了这一行:wat=new Watcher();通过这行:Watcher.Run();我安装了服务并启动了它,它正在工作!当我在文件夹中创建文件时,会创建一个名为“WindowsService3.txt”的文件,以便执行“OnChanged”方法。。。谢谢,对不起:/2天前我才开始使用C。