我有一个包含多个 word 文档的文件夹。我需要监视此文件夹以了解这些 word 文档中的任何更改。我面临以下问题:
FileSystemWatcher
从不报告正在更改的文件的确切名称。例如,对于文件 abc.doc,它会在第一次保存时报告“~$abc.doc 已更改”。- 对于该文件的所有后续保存,不会调用以下代码中的
OnChanged
事件。当我将过滤器更改为watcher.Filter = "*.*"
时,我发现对于后续保存,它会报告“~WRL0001.tmp 已更改”。
所以底线是我永远不知道更改的文件的确切名称。
我正在使用下面的代码
public static void Main()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\Administrator\Documents\"; //"
watcher.NotifyFilter = NotifyFilters.Size;
watcher.Filter = "*.doc";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
最佳答案
File system watcher never reports the exact name of file being changed. For example for file abc.doc, it reports "~$abc.doc is changed" on first save.
这是因为 Word 在打开原始文件的当前目录中创建了几个临时文件,并且在创建新文件时也会触发 FileChanged 事件。事实上,FileSystemWatcher 会触发 FileCreated,然后触发 FileChanged 事件。由于您没有订阅 FileCreated,因此您只会看到 FileChanged 通知。
For all subsequent saves to that file, OnChanged event in the following code is not called. When I changed the filter to watcher.Filter = ".", I found that for subsequent saves, it reports "~WRL0001.tmp is changed".
同上。
但我很好奇你的问题,我对你的程序做了一点改动,修改如下(只贴出相关行):
watcher.NotifyFilter = NotifyFilters.Attributes;
watcher.Filter = "*.doc";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
然后我在保存文件时看到正在更改的文件的实际名称打印在控制台上。当我查看从一次保存到下一次保存时原始文档中哪些属性发生了变化时,我注意到修订号增加了 1(我知道,从操作系统的角度来看,修订号不是文件属性)。我敢肯定其他属性——找不到更好的词了——已经改变了。如果您想将 NotificationFilter
设置为 NotifyFilters.Attributes;
以使其正常工作,这完全取决于您,但是如果让 NotificationFilter =NotifyFilters.Size | NotifyFilters.LastWrite;
例如。
关于c# - 无法使用 FileSystemWatcher 监视 word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7564158/