Using a FileSystemWatcher with Windows Service

18.7k views Asked by At

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!

1

There are 1 answers

0
Tien Dinh On BEST ANSWER

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