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



我这样做正确吗?

问题:
编写一个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为null,因为该事件不在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");
}

最新更新