【问题标题】:Using FileSystemWatcher to monitor file creation and copy it before deleted使用 FileSystemWatcher 监控文件创建并在删除前复制它
【发布时间】: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


【解决方案1】:

选项 1: 而不是查看 FileSystemWatcher,您应该查看挂钩代码以删除事件。 您可以在 Stack Overflow 上查看此评论:https://stackoverflow.com/a/4395147/442470

选项 2: 一旦您的 FileSystemWatcher 意识到文件已创建,请更改该文件的权限,使其无法被删除。

【讨论】:

  • 谢谢大家。 @Yogee - 谢谢......我保持简单,只是更改了权限,所以文件不会被删除。
猜你喜欢
  • 2013-01-18
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多