c# - 使用 Visual Studio 2019 将 FileSystemWatcher 作为 Windows 服务

标签 c# windows-services filesystemwatcher

因此,我创建了一个 Windows 服务,在其中使用 FileSystemWatcher 来监视不同的目录。每次检测到更改的文件时,我都会将它们复制到不同的目录中,以便稍后可以使用它们。

当我将程序作为控制台应用程序运行时,这工作完美

当我将其作为服务运行时,我可以正确启动和停止该服务,但它不会检测到任何类型的事件。 strong> 我尝试调试我的服务,发现错误是由于我没有停止 FileSystemWatcher

对于我的控制台应用程序,我有 Watch() 方法的代码:

    public void Watch()
    {
        using (FileSystemWatcher watcher = new FileSystemWatcher($"C:\\Users\\wost\\AppData\\Roaming\\Sublime", _ext))
        {
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            watcher.IncludeSubdirectories = true;
            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }

因此,如果用户按“q”,我就会停止程序。

对于我的 Windows 服务,我有 Watch() 方法的代码:

 public void Watch()
    {
        using (FileSystemWatcher watcher = new FileSystemWatcher($"C:\\Users\\lashi\\AppData\\Roaming\\Sublime Text 3", _ext))
        {
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            watcher.IncludeSubdirectories = true;
            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

        }
    }

所以,在这里我根本不停止FileSystemWatcher,因为由于我没有与用户直接交互,所以我不知道如何停止它。您能帮我找到解决方案吗?

这些是 OnStart()OnStop() 方法:

public partial class Service1 : ServiceBase
{
    Watcher w;
    
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart()
    {
        w = new Watcher($"C:\\EMMC_CACHE\\expt1-log", $"C:\\EMMC_CACHE\\expt1-file", "lashi");
        w.Watch();
    }

    protected override void OnStop()
    {
        DirectoryInfo dir = new DirectoryInfo(@"C:\Users\wost\Desktop\FILES");
        int count = dir.GetFiles().Length;
        // TEST
        if (count == 0)
        {
            StreamWriter writer = new StreamWriter(@"C:\Users\wost\Desktop\Notes.txt");
            writer.WriteLine("Service is stopped at: " + DateTime.Now);
            writer.Close();
        }
    }
}

最佳答案

我认为你需要让观察者成为一个字段,而不是过早地处理它。我没有测试此代码,但我认为您会在“Watch”中看到相关更改......

internal class Watcher : IDisposable {

    private FileSystemWatcher _watcher;
    private string _directoryPath;  
    private string _ext;
    
    internal Watcher (string directoryPath, string ext) {
            _directoryPath = directoryPath;
            _ext = ext;
    }
    ~Watcher () {
        Dispose();
    }
    public void Watch()
    {
        Dispose();
        
        _watcher = new FileSystemWatcher(_directoryPath, _ext);
        
        _watcher.NotifyFilter = NotifyFilters.LastAccess
                             | NotifyFilters.LastWrite
                             | NotifyFilters.FileName
                             | NotifyFilters.DirectoryName;

        _watcher.IncludeSubdirectories = true;
        // Add event handlers.
        _watcher.Changed += OnChanged;
        _watcher.Created += OnChanged;
        _watcher.Deleted += OnChanged;
        _watcher.Renamed += OnRenamed;

        // Begin watching.
        _watcher.EnableRaisingEvents = true;
    }
    
     public void Dispose() {
        try {
           _watcher?.Dispose();
        } catch {
           ;
        }
        _watcher = null;
     }
     //FSW event handlers...

}

关于c# - 使用 Visual Studio 2019 将 FileSystemWatcher 作为 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68309874/

相关文章:

c# - 提供的类型必须是枚举

c# - 比较两个对象

c# - 是否可以从 Windows 服务打印 PDF 文档?

c++ - Mac OS X 的文件系统观察器

c# - 如何跟踪文件和文件夹的复制/粘贴事件

c# - 在我的蓝牙 LE 设备上,我可以更改外围设备上的特征属性吗?

c# - Blazor 模态表单验证 : You've to click the cancel button twice to close the modal when you delete a form field

c# - sc.exe 将 exe 安装为服务?

service - 如何在Windows XP中安装延迟自动启动类型的服务

c# - 如何知道哪个 FileSystemWatcher 正在调用方法?