Global.asax 文件中的事件侦听器脚本需要不断 运行

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

我这样做正确吗?

问题:
编写一个 asp.net 脚本,持续检查服务器上的目录是否有任何更改

我想到的解决方案:
编写一个侦听器,检查 global.asax 文件

中目录中是否有任何文件已更改

我遇到的问题:

我对这个问题采取的方法是否正确?

这是我在 global.asax 文件中的代码

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 
}

在网站上执行此操作不是文件观察者的理想场所。 但是,您的错误是因为您的 HttpContext.Current 在事件处理程序中为空,因为该事件不在 asp .net 请求管道中。

如果你坚持这样做,那么改变你的代码如下:

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");
}