Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 20, 2015 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/9fa221e70e03e2193a8f to your computer and use it in GitHub Desktop.
Save Fhernd/9fa221e70e03e2193a8f to your computer and use it in GitHub Desktop.
Uso de la clase FileSystemWatcher en C#.
// OrtizOL - xCSw - http://ortizol.blogspot.com
using System;
using System.IO;
using System.Windows.Forms;
namespace Receta.CSharp.R0519
{
public class MonitorCreacionEliminacionArchivo
{
public static void Main()
{
Console.WriteLine(Environment.NewLine);
// Creación del monitor de sistema de archivo:
using (FileSystemWatcher monitor = new FileSystemWatcher())
{
// Ruta a monitorizar:
monitor.Path = Application.StartupPath;
// Tipos de archivos a monitorizar:
monitor.Filter = "*.*";
// Incluir subdirectorios:
monitor.IncludeSubdirectories = true;
// Adición de manejadores (handlers) de evento:
monitor.Created += new FileSystemEventHandler(OnCreatedODeleted);
monitor.Deleted += new FileSystemEventHandler(OnCreatedODeleted);
// Inicio de la monitorización:
monitor.EnableRaisingEvents = true;
Console.WriteLine("Presione Enter para crear un archivo: ");
Console.ReadLine ();
using (FileStream fs = new FileStream("Archivo.bin", FileMode.Create))
{
// Escritura de datos...
}
Console.WriteLine("\nPresione Enter para eliminar un archivo: ");
Console.ReadLine ();
if (File.Exists("Archivo.bin"))
{
File.Delete("Archivo.bin");
}
}
Console.WriteLine(Environment.NewLine);
}
private static void OnCreatedODeleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("\tNotificación: {0} fue -{1}-.", e.FullPath, e.ChangeType.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment