我有以下代码用于监视文本文件的目录,目录每天获取两次新文件,代码可以在某段时间内正常工作,但在此之后它会停止触发OnCreated事件。 。FileSystemWatcher在某段时间不会触发
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public static void Run()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"c:\users\documents\";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Created += new FileSystemEventHandler(OnCreated);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
想不通的问题。
另外,我想知道这种万无一失的选择(如果有的话),因为我没有找到这个可靠..
需要注意的是'FileSystemWatcher'有一点一个不可靠的声誉(尽管我不确定这是否是FileSystemWatcher实现的问题或者它是如何被使用的)。请参阅http://stackoverflow.com/questions/239988/filesystemwatcher-vs-polling-to-watch-for-file-changes以获得有关其他人如何处理该问题的建议。 –
另外,我的理解是'FileSystemWatcher'使用系统的'ReadDirectoryChangesW' API。 Jim Beveridge在该API的详细信息中阅读本文可能会有帮助:http://qualapps.blogspot.com/2010/05/understanding-readdirectorychangesw.html –