4

Background Infomation: I am using FileSystemWatcher class implemented in a service to monitor changes in the files. Heres the section of coding that throws an Argument Exception (Path is not a legal form) when the onCreate event is triggered.

FileMonitor.CS

public partial class FileMonitor:ServiceBase
{
 public FileSystemWatcher Watcher = new FileSystemWatcher();

    Private void FileWatcher()
    {
    FileActionHandler ActionHandler = new FileActionHandler();
    Watcher.Created += new FileSystemEventHandler(ActionHandler.onCreate);
    Watcher.Deleted += new FileSystemEventHandler(ActionHandler.onDelete);
    Watcher.Renamed += new RenamedEventHandler(ActionHandler.onRenamed);
    Watcher.EnableRaisingEvents = true;
    }
}

FileActionHandler.CS

 class FileActionHandler
 {
  FileMonitor FileMon = new FileMonitor();
  public void onCreate/onRename/onDelete(object source, FileSystemEventArgs e)
    {
      try
      {
       FileMon.Watcher.EnableRaisingEvents = false;
      }
      catch
      {
       /* Exception Code */
      }
      finally
      {
       FileMon.Watcher.EnableRaisingEvents = true;
      }
    }
  }

Question: Can anyone advice me on why is the exception being thrown and how I can go about resolving it ?

Derek
  • 2,185
  • 4
  • 20
  • 24
  • Which line throws the exception? – Andrew Cooper Aug 19 '11 at 04:13
  • Thats the problem. I dont know which line throws the exception. But I narrowed down to this section of the code which resulted in the exception being thrown. – Derek Aug 19 '11 at 04:14
  • I'm guessing you have simplified your code before posting it here.can you post your actual code? – kay.one Aug 19 '11 at 04:28
  • My actual entire code works fine while I use the FileSystemWatcher to monitor changes in the file. But ever since I added this section of the code, exception was being thrown and my service would stop working. Somewhere in this section throws the error. – Derek Aug 19 '11 at 04:36
  • Can you connect a debugger to the service to see where it's falling over? – Andrew Cooper Aug 19 '11 at 04:49
  • Could you check if my coding is appropriate ? Like the use of objects from one class to another. – Derek Aug 19 '11 at 05:59
  • Hmm at first glance it looks alright. Have you tried debugging by logging to files? E.g. print exception stacktrace to a file? When is "FileWatcher()" called btw? – Johny Skovdal Aug 19 '11 at 06:22

1 Answers1

9

I ran into the same issue when I did mine a few weeks ago. What I found was that you need to set the path before you set anything else. So, right after you declare the object:

FileSystemWatcher watchfolder = new FileSystemWatcher();
watchfolder.Path = ConfigurationManager.AppSettings["MonitorPath"];

You can read more here: Create a file watcher service for windows

I hope this helps

Dustin Davis
  • 14,482
  • 13
  • 63
  • 119
Savage
  • 91
  • 1