我这样做是否正确?
问题:
编写一个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
}
答案 0 :(得分:0)
在网站上执行此操作不是文件观察程序的理想位置。 但是,您的错误是因为您的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");
}