Created
July 20, 2015 23:22
-
-
Save Fhernd/785785cbb87df0679937 to your computer and use it in GitHub Desktop.
Uso de la clase FileSytemWatcher.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.IO; | |
using System.Security.Permissions; | |
namespace Receta.CSharp.R0519 | |
{ | |
public class Monitor | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine(Environment.NewLine); | |
EjecutarMonitor(); | |
Console.WriteLine(Environment.NewLine); | |
} | |
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")] | |
public static void EjecutarMonitor() | |
{ | |
string[] args = System.Environment.GetCommandLineArgs(); | |
// Valida el número de argumentos introducidos | |
// por el usuario: | |
if (args.Length != 2) | |
{ | |
Console.WriteLine("Uso: Monitor.exe (directorio)"); | |
return; | |
} | |
// Creación de objeto FileSystemWatcher: | |
FileSystemWatcher monitor = new FileSystemWatcher(); | |
// Directorio a monitorizar: | |
monitor.Path = args[1]; | |
// Cambios a monitorizar: | |
monitor.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | |
| NotifyFilters.FileName | NotifyFilters.DirectoryName; | |
// Tipos de archivos a monitorizar: | |
monitor.Filter = "*.txt"; | |
// Adición de manejadores de eventos: | |
monitor.Changed += new FileSystemEventHandler(OnChanged); | |
monitor.Created += new FileSystemEventHandler(OnChanged); | |
monitor.Deleted += new FileSystemEventHandler(OnChanged); | |
monitor.Renamed += new RenamedEventHandler(OnRenamed); | |
// Inicio de la monitorización: | |
monitor.EnableRaisingEvents = true; | |
Console.WriteLine(args[1]); | |
// El usuario finaliza el programa con presionar | |
// la tecla q: | |
Console.WriteLine("Presione \'q\' para finalizar la monitorización."); | |
while (Console.Read() != 'q'); | |
} | |
// Manejador de cambios sobre el archivo: Changed, Created, y Deleted: | |
private static void OnChanged(object source, FileSystemEventArgs e) | |
{ | |
Console.WriteLine ("El archivo {0} fue {1}.", e.FullPath, e.ChangeType); | |
} | |
// Manejador evento de renombrado: Renamed | |
private static void OnRenamed(object source, RenamedEventArgs e) | |
{ | |
Console.WriteLine("El archivo {0} fue renombrado a {1}", e.OldFullPath, e.FullPath); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment