Windows Service w/ FileSystemWatcher in C#

喜夏-厌秋 提交于 2019-12-05 02:25:18

If you're making a Window's service, then you'll want to do it programmatically. I usually keep forms out of my services and make a separate interface for them to communicate. Now the FileSystemWatcher doesn't have an event to watch solely for size, so you'll want to make a method that ties to FileSystemWatcher.Changed to check for modifications to existing files. Declare and initialize the control in your OnStart method and tie together the events as well. Do any cleanup code in your OnStop method. It should look something like this:

protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher("PATH HERE");
Watcher.EnableRaisingEvents = true;
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
} 

// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
// your code here
}

Also note, the FileSystemWatcher will fire off multiple events for a single file, so when you're debugging watch for patterns to work around it.

You can simply enable your filesystemwatcher object in the OnStart method by setting

EnableRaisingEvents = true;

Then handle the event. That should do it.

you can create a delegate to handle what has changed like

myWatcher.Changed += new FileSystemHandler(FSWatcherTest_Changed);

private void FSWatcherTest_Changed(object sender, 
                System.IO.FileSystemEventArgs e)
{
    //code here for newly changed file or directory
}

And so on

I would recommend you to read this article http://www.codeproject.com/Articles/18521/How-to-implement-a-simple-filewatcher-Windows-serv

Also have this delegate on_start in windows service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!