我正在嘗試監視我的 asp.net mvc5 項目中的文件夾。我想把它放在 Startup.cs 中,在那里我初始化我的 FileSystemWatcher。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' 方法沒有被觸發,無論我在文件夾中做什么。我按照微軟的例子:https ://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher( v= vs.110) .aspx讓我知道我做錯了什么。
1 回答

慕后森
TA貢獻1802條經驗 獲得超5個贊
您似乎在方法中創建了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.
- 1 回答
- 0 關注
- 320 瀏覽
添加回答
舉報
0/150
提交
取消