Listens to the file system change notifications and raises events : FileSystemWatcher « File Stream « C# / C Sharp






Listens to the file system change notifications and raises events

  

using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{

    public static void Main()
    {
        Run();
    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = "c:\\";
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.txt";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);
        watcher.EnableRaisingEvents = true;
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }
    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}

   
    
  








Related examples in the same category

1.Set NotifyFilter of FileSystemWatcher
2.On file created or deleted
3.File Watcher