我正在尝试监视asp.net mvc5项目中的文件夹。而且我想到了将它放在初始化FileSystemWatcher的Startup.cs中。
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);
}
}
现在,创建观察者,但是无论我在文件夹中做什么,都不会触发'loadFile'方法。 我遵循了Microsoft的示例: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
让我知道我在做错什么。
答案 0 :(得分:0)
您似乎在方法中将FileSystemWatcher
创建为局部变量。当然,这将在方法结束时超出范围,并且很可能会在此时进行整理,然后删除手表。
尝试在Startup.cs中将FSW创建为私有对象
public class Startup
{
private FileSystemWatcher watcher {get;set;}
public Startup(IApplicationEnvironment env,
IHostingEnvironment hostenv, ILoggerFactory logger)
{
//your setup FSW
{
}
接下来,尝试仅使用NotifyFilters.LastWrite
。