[英]FileSystemWatcher as a Windows Service using Visual Studio 2019
[英]Using a FileSystemWatcher with Windows Service
我有一个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个文件,然后自动停止。 是什么让服务自动停止? 当我检查事件日志时,我没有看到错误或警告!
一旦它超出范围,你的局部变量fp就会被处理掉。 解决方案是将其声明为实例变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.