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

无人久伴 提交于 2019-12-01 02:10:54
David Brabant

Set up the watcher:

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

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

watcher.Created += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEvents = true;

Then implement the FileCreated delegate:

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

Please look here for a detailed explanation of the FileSystemWatcher: http://www.c-sharpcorner.com/uploadfile/mokhtarb2005/fswatchermb12052005063103am/fswatchermb.aspx

You will have to look for created files if you want to look for added files.

You specify the type of change to watch for by setting the value of a WatcherChangeType enumeration. The possible values are as follows:

  • All: The creation, deletion, change, or renaming of a file or folder.
  • Changed: The change of a file or folder. The types of changes include: changes to size, attributes, security settings, last write, and last access time.
  • Created: The creation of a file or folder.
  • Deleted: The deletion of a file or folder.
  • Renamed: The renaming of a file or folder.

Also you may just wire up the event handler that fires if a file is created (added) and not implement all the other events since they are not interesting for you:

watcher.Created += new FileSystemEventHandler(OnChanged);

Code with comments below may hopefully satisfy your needs.

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
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!