【发布时间】:2014-09-20 03:34:45
【问题描述】:
我们有一个第 3 方应用程序,它将文件写入目录然后将其删除。 我们想在该文件被删除之前复制它。
我们有这个:
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。
我想仔细检查一下我对文件为何为空的想法。是不是因为文件被第 3 方应用程序删除得太快以至于它没有机会进行正确的复制? 感谢您的观看。
【问题讨论】:
-
如果在创建文件时通知您,没有关闭,则第 3 方应用程序可能尚未写入任何数据。您不能使用
FileSystemWatcher来确保您有机会在文件写入和关闭之后、但在删除之前访问该文件。 -
正确的临时文件是通过不共享 + 关闭时删除打开的,因此您可能需要更低级别的代码来拦截内容,因为正常的访问检查会阻止常规用户级别的代码访问文件。
-
文件系统过滤驱动是你的朋友。
标签: c# filesystemwatcher