Search code examples
c#asp.netfilesystemwatcher

Event Listener script in Global.asax file needs to constantly run


Am I doing this correctly?

Problem:
To write a asp.net script that continuously checks to see if any changes were made to a directory on a server

Solution I came up with:
write a listener that checks to see if there are any files in the directory that have changed in the global.asax file

Problems I am having:

  • Event handler is not firing when changes to the directory happen.
  • Ensuring the script is always running on server.

Am I taking the right approach to this problem?

Here is my code in the global.asax file

FileSystemWatcher watcher;
//string directoryPath = "";

protected void Application_Start(Object sender, EventArgs e)
{
    string directoryPath = HttpContext.Current.Server.MapPath("/xmlFeed/");
    watcher = new FileSystemWatcher();
    watcher.Path = directoryPath;
    watcher.Changed += somethingChanged;

    watcher.EnableRaisingEvents = true;
}
void somethingChanged(object sender, FileSystemEventArgs e)
{
    DateTime now = DateTime.Now;
    System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("/debug.txt"), "(" + "something is working" + ")  " + now.ToLongTimeString() + "\n");//nothing is getting written to my file 
}

Solution

  • Doing this in the website is not the ideal place for a file watcher. However, your error is because your HttpContext.Current is null in the event handler because the event is not in the asp .net request pipeline.

    If you insist on doing it this way, then change your code like this:

    private FileSystemWatcher watcher;
    private string debugPath;
    void Application_Start(object sender, EventArgs e)
    {
        string directoryPath = HttpContext.Current.Server.MapPath("/xmlFeed/");
        debugPath = HttpContext.Current.Server.MapPath("/debug.txt");
        watcher = new FileSystemWatcher();
        watcher.Path = directoryPath;
        watcher.Changed += somethingChanged;
    
        watcher.EnableRaisingEvents = true;
    }
    void somethingChanged(object sender, FileSystemEventArgs e)
    {
        DateTime now = DateTime.Now;
        System.IO.File.AppendAllText(debugPath, "(something is working)" + now.ToLongTimeString() + "\n");
    }