繁体   English   中英

我需要使用哪个FileSystemWatcher过滤器来查找新文件

[英]Which filter of FileSystemWatcher do I need to use for finding new files

到目前为止,我知道FileSystemWatcher可以查看一个文件夹,如果该文件夹中的任何文件被更改,修改,.etc ...然后我们就可以处理它。 但我不确定在我的场景中应该使用哪个过滤器和事件:观察文件夹,如果文件被添加到该文件夹​​,请执行XYZ ...所以在我的场景中我不关心现有文件是否已更改等等。应该忽略这些...当且仅当新文件被添加到该文件夹​​时才执行XYZ ...

您为此方案推荐了哪个事件和过滤器?

设置观察者:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "Blah";

watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
    | NotifyFilters.FileName;

watcher.Created += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEvents = true;

然后实现FileCreated委托:

private void OnChanged(object source, FileSystemEventArgs e) {
    Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

请查看FileSystemWatcher的详细说明: http//www.c-sharpcorner.com/uploadfile/mokhtarb2005/fswatchermb12052005063103am/fswatchermb.aspx

如果要查找添加的文件,则必须查找已创建的文件。

您可以通过设置WatcherChangeType枚举的值来指定要监视的更改类型。 可能的值如下:

  • 全部:创建,删除,更改或重命名文件或文件夹。
  • 已更改:文件或文件夹的更改。 更改类型包括:更改大小,属性,安全设置,上次写入和上次访问时间。
  • 已创建:创建文件或文件夹。
  • 已删除:删除文件或文件夹。
  • 重命名:重命名文件或文件夹。

此外,您可以连接在创建(添加)文件时触发的事件处理程序,并且不实现所有其他事件,因为它们对您不感兴趣:

watcher.Created += new FileSystemEventHandler(OnChanged);

下面带有评论的代码可能有望满足您的需求。

public void CallingMethod() {

         using(FileSystemWatcher watcher = new FileSystemWatcher()) {
          //It may be application folder or fully qualified folder location
          watcher.Path = "Folder_Name";

          // Watch for changes in LastAccess and LastWrite times, and
          // the renaming of files or directories.
          watcher.NotifyFilter = NotifyFilters.LastAccess |
           NotifyFilters.LastWrite |
           NotifyFilters.FileName |
           NotifyFilters.DirectoryName;

          // Only watch text files.if you want to track other types then mentioned here
          watcher.Filter = "*.txt";

          // Add event handlers.for monitoring newly added files          
          watcher.Created += OnChanged;


          // Begin watching.
          watcher.EnableRaisingEvents = true;

         }


        }

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e) {
        // Specify what is done when a file is  created with these properties below
        // e.FullPath , e.ChangeType
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM