Using a FileSystemWatcher with Windows Service

Sai picture Sai · Jun 14, 2015 · Viewed 14.6k times · Source

I have a windows service which needs to monitor a directory for files and then move it to another directory. I am using a 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 I install and start the service, it works fine for 1 file and then stops automatically. What is making the service stop automatically? When I check the event log I don't see an error or warning!

Answer

Tien Dinh picture Tien Dinh · Jun 14, 2015

Your local variable fp get disposed off once it goes out of scope. The solution is to declare it as an instance variable instead