0

I'm trying to monitor a folder in my asp.net mvc5 project. And I thought of putting it in the Startup.cs where I initialize my FileSystemWatcher.

public static void initializeWatcher()
    {
        string importPath = @"\\server\Exchange\Inbox", importFilterType = "*.xml";
        try
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = importPath;
            watcher.Filter = ".xml";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
            watcher.Created += new FileSystemEventHandler(loadFile);
            watcher.Changed += new FileSystemEventHandler(loadFile);
            watcher.EnableRaisingEvents = true;
        }
        catch (Exception e)
        {

        }
    }

    private static void loadFile(object source, FileSystemEventArgs e)
    {
        xmlDocument.LoadXml(e.FullPath);
    }
}

Now, the watcher gets created but the 'loadFile' method is not being triggered, no matter what I don in the folder. I followed the example from microsoft: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

Let me know what I'm doing wrong.

badbyte
  • 83
  • 1
  • 10

1 Answers1

0

You seem to be creating the FileSystemWatcher as a local variable in the method. This will of course go out of scope at the end of the method and may well be getting tidied up at that point, then remove the watches.

Try creating the FSW as a private object in Startup.cs

public class Startup
{
    private FileSystemWatcher watcher {get;set;}

    public Startup(IApplicationEnvironment env,
               IHostingEnvironment hostenv,  ILoggerFactory logger)
    {
       //your setup FSW
    {
}

Next, try using only NotifyFilters.LastWrite.

Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • I have added FileSystemWatcher as a private attribute to the class 'Startup' and added the lines of initialization to the method Configuration. I also added the methods loadFile, that should get triggered when a file gets created or changed along into the Class 'Startup', put a breakpoint to it. but nothing happens. – badbyte Jul 24 '18 at 14:01
  • In my case; I only use NotifyFilter = NotifyFilters.LastWrite. Can you try this – Antoine V Jul 24 '18 at 14:07