[英]FileSystemWatcher.WaitForChanged returns, but there is still a lock on the file
[英]C# FileSystemWatcher WaitForChanged Method only detects one file change
我遇到了类似这样的问题: 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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.