【问题标题】:FileSystemWatcher can not detect the change of 1 file (add a new file), only detect atleast 2 filesFileSystemWatcher 无法检测到 1 个文件的变化(添加新文件),只能检测到至少 2 个文件
【发布时间】:2019-12-13 10:49:36
【问题描述】:

FileSystemWatcher 无法检测到 1 个文件的变化(添加新文件),只能检测到至少 2 个文件。 watcher 仅在以下情况下调用 Changed 事件:

  • 将超过 1 个文件复制到 C:\PortViewer
  • 仅将 1 文件复制到 C:\PortViewer,我必须在 文件资源管理器中打开 C:\PortViewer Windows
        FileSystemWatcher watcher;
        private void StartWatcher()
        {
            Directory.CreateDirectory(@"C:\PortViewer");
            watcher = new FileSystemWatcher();
            watcher.Path = @"C:\PortViewer";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter = "*.*";
            watcher.Changed += (s,e) => { /*Do work here*/ };
            watcher.EnableRaisingEvents = true;
        }

【问题讨论】:

  • 该对象还有更多事件,查看Created事件。
  • 谢谢@LasseV.Karlsen,我找到了问题。我必须改用NotifyFilters.CreatedTime
  • 如果这个问题没有被标记为某种重复,您应该留下自己的答案并接受它,以便未来的访问者更容易看到如何解决类似的问题。

标签: c# filesystemwatcher


【解决方案1】:

NotifyFilters.CreatedTime 是解决方案:

        FileSystemWatcher watcher;
        private void StartWatcher()
        {
            Directory.CreateDirectory(@"C:\PortViewer");
            watcher = new FileSystemWatcher();
            watcher.Path = @"C:\PortViewer";
            watcher.NotifyFilter = NotifyFilters.CreatedTime;
            watcher.Filter = "*.*";
            watcher.Changed += (s,e) => { /*Do work here*/ };
            watcher.EnableRaisingEvents = true;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2021-12-08
    相关资源
    最近更新 更多