c# FileSystemWatcher WaitForChanged方法只检测一个文件更改

本文关键字:一个 文件 WaitForChanged FileSystemWatcher 方法 检测 | 更新日期: 2023-09-27 18:17:10

我得到了一个类似的问题: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,正如您所看到的,但它没有帮助。

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

c# FileSystemWatcher WaitForChanged方法只检测一个文件更改

我会更改您的设计,以便您不依赖于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");
    }
}