Basic FileWatcher

suggest change

The following example creates a FileSystemWatcher for the directory in path. It watches LastWrite and LastAccess times, and file or directory name changes, for names matching *.txt. The Changed handler prints the path and change type. Created, Deleted, and Renamed are separate events and are not subscribed here. Renamed is what reports the old and new paths.

The types are in System.IO.

FileSystemWatcher watcher;

private void watch()
{
  // Create a new FileSystemWatcher and set its properties.
  watcher = new FileSystemWatcher();
  watcher.Path = path;

 /* 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.      
  watcher.Filter = "*.txt";

  // Add event handler.
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  // Begin watching.      
  watcher.EnableRaisingEvents = true;
}

// Define the event handler.
private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory or another action.
  Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents