Reputation: 712
Hi developing friends!
Situation: I have a small service for some simple file exchange jobs to move files from one system to another and do some search and replace/unzip stuff. The service written in C# uses the FileSystemWatcher to check for new files in the folder. The Code:
private static void Main(string[] args)
{
try
{
InitializeService();
}
catch (Exception ex)
{
}
fsw = new FileSystemWatcher();
fsw.Path = RootPath;
//Watch only directories
fsw.NotifyFilter = NotifyFilters.DirectoryName;
//Add the event functions
fsw.Created += FileSystemEvent;
//fsw.Changed += FileSystemEvent;
fsw.Error += OnError;
//start the listener
fsw.EnableRaisingEvents = true;
Console.WriteLine("Started with path: " + RootPath);
Console.ReadLine();
}
Problem description: The path for the filewatcher is on another server, so I'm connecting to a share. From time to time the filewatcher loses the connection to the directory (network issue, server reboot during maintenance window or what ever). If this happens the filewatcher does not reconnect to the server or throw an exception or any other indication that he's no longer connected. Just does nothing!
Question Is there anything I can do to check if the filewatcher has lost the connection? Because my workaround now is that I restart the server every night with a scheduled job and check first for existing files and process them before. But that's not what I think should be the idea if you use a filewatcher.
Many thanks
Upvotes: 2
Views: 1030
Reputation: 14251
Perhaps the garbage collector removes the FileSystemWatcher instance.
Try GC.KeepAlive:
Console.ReadLine();
GC.KeepAlive(fsw);
Upvotes: 3
Reputation: 5733
Have you tried to put all the FSW-stuff inside a method with a try-catch? When the method exits you could simply call it again in a while-loop like this (pseudo):
private static void Main(string[] args)
{
while (true)
{
CallWatcher();
}
}
private static void CallWatcher()
{
var watcher = new FileSystemWatcher();
try
{
// do watcher stuff here
}
finally
{
watcher.Dispose();
}
}
Upvotes: 0