C#FileSystemWatcher WaitForChanged方法仅检测一个文件更改

我遇到了类似这样的问题: FileSystemWatcher – 只有一次触发更改事件?

但由于该线程已有两年,我的代码有点不同,我决定开一个新问题。

好吧,这是我的代码:

while (true) { FileSystemWatcher fw = new FileSystemWatcher(); fw.Path = @"Z:\"; fw.Filter = "*.ini"; fw.WaitForChanged(WatcherChangeTypes.All); Console.WriteLine("File changed, starting script..."); //if cleanup try { if (File.ReadAllLines(@"Z:\file.ini")[2] == "cleanup") { Console.WriteLine("Cleaning up..."); Process c = new Process(); c.StartInfo.FileName = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop).Trim('\\') + @"\clean.exe"; c.StartInfo.WorkingDirectory = System.Environment.SpecialFolder.DesktopDirectory.ToString(); c.Start(); c.WaitForExit(); Console.WriteLine("Done with cleaning up, now starting script..."); } } catch { Console.WriteLine("No cleanup parameter found."); } Process p = new Process(); p.StartInfo.FileName = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop).Trim('\\') + @"\go.exe"; p.StartInfo.WorkingDirectory = System.Environment.SpecialFolder.DesktopDirectory.ToString(); p.Start(); Console.WriteLine("Script running..."); p.WaitForExit(); fw = null; Console.WriteLine("Done. Waiting for next filechange..."); } 

问题:该程序应检测文件“Z:\ file.ini”中的文件更改。 如果它已更改,则应触发脚本。 当脚本完成后,程序应该返回到开始并再次开始观察更改(这就是我使用while循环的原因)。 好吧,检测到第一个更改,一切似乎都正常工作,但是第一个更改后的任何更改都不会被检测到。 我试图将FileSystemWatcher对象设置为null,如您所见,但它没有帮助。

所以,我希望得到好的答案。 谢谢。

我会更改您的设计,因此您不必依赖FileSystemWatcher进行任何更改。 而是轮询您正在观看任何更改的目录或文件。 然后,如果我们知道有更改,您可以将FileSystemWatcher与此结合使用以尽快将其唤醒。 这样,如果您错过了某个活动,您仍然会根据您的轮询超时从中恢复。

例如

 static void Main(string[] args) { FileSystemWatcher watcher = new FileSystemWatcher(@"f:\"); ManualResetEvent workToDo = new ManualResetEvent(false); watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Changed += (source, e) => { workToDo.Set(); }; watcher.Created += (source, e) => { workToDo.Set(); }; // begin watching watcher.EnableRaisingEvents = true; while (true) { if (workToDo.WaitOne()) { workToDo.Reset(); Console.WriteLine("Woken up, something has changed."); } else Console.WriteLine("Timed-out, check if there is any file changed anyway, in case we missed a signal"); foreach (var file in Directory.EnumerateFiles(@"f:\")) Console.WriteLine("Do your work here"); } }