TMOTTM
TMOTTM

Reputation: 3381

Windows Service with FileSystemWatcher stops after the first event

I'm building a simple Windows Service (basically combining this tutorial with this class).

Now I have a "FROM" directory and two "TO" (TO1, TO2) directories. When I place a file into FROM, it should be copied both to TO1 and TO2. I install the service and I start it in the Service Control Manager where I see it's running. On the first run, it copies the file to TO1 and TO2 and the service is still running after that. Then, when I place another file to FROM (with a different name), nothing happens. And refreshing the services I find that the service stopped.

Why does the service stop? It seems it stops just in the moment when I place the second file.

Here I register the file system watcher:

    // File System Watcher
    var fileSystemWatcher = new FileSystemWatcher();
    fileSystemWatcher.Created += FileSystemWatcher_MoveOnCreate;
    fileSystemWatcher.Path = this.fromPath;
    fileSystemWatcher.EnableRaisingEvents = true;

And here is the event handler:

private void FileSystemWatcher_MoveOnCreate(object sender, FileSystemEventArgs e)
{
    string FROM = Path.Combine(fromPath, e.Name);
    string TO1 = Path.Combine(toPathOne, e.Name);
    string TO2 = Path.Combine(toPathTwo,  e.Name);

    File.Copy(FROM, TO1);
    File.Copy(FROM, TO2)
}

Upvotes: 0

Views: 1024

Answers (1)

Felice Pollano
Felice Pollano

Reputation: 33252

If the Windows Service stops there was an unhandled exception in your code somewhere. Try to surround the key point of your code ( maybe the entire body of the function FileSystemWatcher_MoveOnCreate ) with try{}catch(){} and log what's happening. In general you should add log to your windows service is the only way you can understand if things are going on anyway.

Upvotes: 2

Related Questions