Using FileSystemWatcher with Windows Service

I have a windows service that needs to monitor a directory for files and then move it to another directory. I am using FileSystemWatcher to implement this.

This is my main service class.

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()
    {

    }
}

      

This is my FileProcessor class

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

      

After installing and starting the service, it works fine for 1 file and then stops automatically. What makes the service stop automatically? When I check the event log, I don't see an error or warning!

+3


source to share


1 answer


The local variable fp is removed when it goes out of scope. The solution is to declare it as an instance variable instead of



+7


source







All Articles