C#: FileSystemWatcher

Ecco un esempio di utilizzo. Talmente semplice che non necessita di grandi spiegazioni:

using System;
using System.IO;</code>
 
<code>namespace IlMioBelNamespace
{
/// <summary>
/// La mia bella classe che monitora quello che succede in una directory
/// </summary>
public class LaMiaBellaClasse
{
   FileSystemWatcher watcher;
 
   public void start()
   {
 
      // Creo il nuovo oggetto FileSystemWatcher.
      watcher = new FileSystemWatcher();
 
      // Posso filtrare dal nome del file o dalla sua estensione.
      watcher.Filter = "*.txt";
 
      // Sottoscrivo l'evento Created
      watcher.Created += new  FileSystemEventHandler(watcher_FileCreated);
 
      // Sottoscrivo l'evento Changed
      watcher.Changed += new  FileSystemEventHandler(watcher_FileChanged);
 
      // Sottoscrivo l'evento Deleted
      watcher.Deleted += new  FileSystemEventHandler(watcher_FileDelete);
 
      // Sottoscrivo l'evento Renamed
      watcher.Renamed += new System.IO.RenamedEventHandler(watcher_FileRenamed);
 
      // Imposto il Path
      watcher.Path = @"c:\incoming"
 
      // Si parte!
      watcher.EnableRaisingEvents = true;
 
   }
 
   void watcher_FileCreated(object sender, FileSystemEventArgs e)
   {
      // e' stato creato un file
   }
 
   void watcher_FileChanged(object sender, FileSystemEventArgs e)
   {
      // è stato modificato un file
   }
 
   void watcher_FileDelete(object sender, FileSystemEventArgs e)
   {
      // è stato cancellato un file
   }
 
   void watcher_FileRenamed(object sender, System.IO.RenamedEventArgs e)
   {
      // è stato rinominato un file
   }
 
}
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>