我们有第三方应用程序将文件写入目录并删除它。 我们希望在删除文件之前复制该文件。使用FileSystemWatcher监视文件创建并在删除之前将其复制
我们有这样的:
FileSystemWatcher watcher;
private void WatchForFileDrop()
{
watcher = new FileSystemWatcher();
watcher.Path = "c:\\FileDrop";
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Filter = "*.txt";
watcher.Created += new FileSystemEventHandler(OnCreated);
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
//Copy the file to the file drop location
System.IO.File.Copy(e.FullPath, "C:\\FileDropCopy\\" + e.Name);
}
的FileSystemWatcher的确实工作。它会看到文件已经创建并转到OnCreated()。该文件在目录中创建。
唯一的问题是文件是空的,文件大小是0kb。
我想仔细检查一下为什么文件是空的。是否因为第三方应用程序很快删除了该文件,因此它没有机会进行正确的复制? 谢谢你看看。
如果在文件创建时收到通知,没有关闭,那么第三方应用程序可能还没有写入任何数据。您不能使用FileSystemWatcher来确保在写入和关闭文件之后,但在删除文件之前有机会访问该文件。 – HABO 2014-09-19 19:07:09
适当的临时文件是通过不共享+ delete-on-close打开的,因此您可能需要更低级别的代码来拦截内容,因为正常的访问检查将阻止常规用户级代码访问文件。 – 2014-09-19 19:23:56
文件系统过滤器驱动程序是你的朋友。 – 2014-09-19 20:11:27