我测试了这个代码近30次,我在控制台中看到的消息只有10-15次。 (必须在事件发生时出现。)
string fileToWatchFor = "file.txt";
var inputedFileInfo = new FileInfo(fileToWatchFor);
FileSystemWatcher fileSystemWatcher
= new FileSystemWatcher(inputedFileInfo.DirectoryName);
fileSystemWatcher.Filter = "*.txt";
fileSystemWatcher.Deleted += delegate (object sender, FileSystemEventArgs eventArgs)
{ Console.WriteLine("I was invoked when you file was deleted!"); };
fileSystemWatcher.EnableRaisingEvents = true;
File.Create(fileToWatchFor).Close();
File.Delete(fileToWatchFor);
我读了很多答案并试图做到以下几点:
GC.KeepAlive(fileSystemWatcher);
但无论如何它都无济于事。我以管理员权限运行VS.
我有Windows 10,VS 2017,使用.NET Framework 4.6.1在调试模式下运行项目。
inputedFileInfo.DirectoryName
的目录是正确的,File.Create(fileToWatchFor)
的结果放在此目录中。 (我已多次检查过。)