Controlar las modificaciones de un fichero mediante las notificaciones de sistema

1900 vistas

Windows envía notificaciones que permiten controlar las modificaciones realizadas a un sistema de ficheros.
Para poderlo controlar usaremos la clase System.IO.FileSystemWatcher.



vbnet
  1. Imports System.IO
  2.  
  3.     Sub Watch(ByVal sPath As String, Optional ByVal sFilter As String = "*")
  4.         ' podemos usar los '*' con el filtro
  5.  
  6.         ' creación del objeto watcher
  7.         Dim fw As New FileSystemWatcher(sPath, sFilter)
  8.  
  9.         ' adjuntamos los handlers para controlar los eventos que queramos controlar.
  10.         AddHandler fw.Changed, AddressOf OnChanged
  11.         AddHandler fw.Renamed, AddressOf OnRenamed
  12.         AddHandler fw.Created, AddressOf OnChanged
  13.         AddHandler fw.Deleted, AddressOf OnChanged
  14.         AddHandler fw.Error, AddressOf OnError
  15.  
  16.         ' controlaremos también las subcarpetas
  17.         fw.IncludeSubdirectories = True
  18.         ' para poner en marcha el control, tendremos que poner a true EnableRaisingEvents.
  19.         ' poniéndolo a false, se parará el control.
  20.         fw.EnableRaisingEvents = True
  21.  
  22.     End Sub
  23.  
  24.     Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
  25.         Console.WriteLine("Fichero {0} {1}", e.FullPath, e.ChangeType)
  26.     End Sub
  27.  
  28.     Sub OnRenamed(ByVal source As Object, ByVal e As RenamedEventArgs)
  29.         Console.WriteLine("Fichero {0} renombrado a {1}", e.OldFullPath, e.FullPath)
  30.     End Sub
  31.  
  32.     Sub OnError(ByVal source As Object, ByVal e As ErrorEventArgs)
  33.         Dim ex As Exception = e.GetException()
  34.         Debug.WriteLine(ex.ToString())
  35.         Console.WriteLine(ex.Message)
  36.     End Sub



y aquà cómo usar esta función Watch



vbnet
  1. Watch("c:\mifichero.txt")
  2.     ' O
  3. Watch("c:\*.*")