在Windows服务中使用FileSystemWatcher

时间:2015-06-14 14:31:07

标签: c# windows-services filesystemwatcher

我有一个Windows服务需要监视目录中的文件,然后将其移动到另一个目录。我正在使用FileSystemWatcher来实现它。

这是我的主要服务类。

public partial class SqlProcessService : ServiceBase
{
    public SqlProcessService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        FileProcesser fp = new FileProcesser(ConfigurationManager.AppSettings["FromPath"]);
        fp.Watch();
    }

    protected override void OnStop()
    {

    }
}

这是我的FileProcessor类

public class FileProcesser
{
    FileSystemWatcher watcher;
    string directoryToWatch;
    public FileProcesser(string path)
    {
        this.watcher = new FileSystemWatcher();
        this.directoryToWatch = path;
    }
    public void Watch()
    { 
        watcher.Path = directoryToWatch;
        watcher.NotifyFilter = NotifyFilters.LastAccess |
                     NotifyFilters.LastWrite |
                     NotifyFilters.FileName |
                     NotifyFilters.DirectoryName;
        watcher.Filter = "*.*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        File.Copy(e.FullPath, ConfigurationManager.AppSettings["ToPath"]+"\\"+Path.GetFileName(e.FullPath),true);
        File.Delete(e.FullPath);
    }
}   

安装并启动服务后,它可以正常运行1个文件,然后自动停止。是什么让服务自动停止?当我检查事件日志时,我没有看到错误或警告!

1 个答案:

答案 0 :(得分:9)

当局部变量fp超出范围时,它会被处理掉。解决方案是将其声明为实例变量