On file created or deleted : FileSystemWatcher « File Stream « C# / C Sharp






On file created or deleted

  


using System;
using System.IO;
using System.Windows.Forms;

class MainClass {
    static void Main(string[] args) {
        using (FileSystemWatcher watch = new FileSystemWatcher()) {
            watch.Path = Application.StartupPath;
            watch.Filter = "*.*";
            watch.IncludeSubdirectories = true;

            // Attach the event handler.
            watch.Created += new FileSystemEventHandler(OnCreatedOrDeleted);
            watch.Deleted += new FileSystemEventHandler(OnCreatedOrDeleted);
            watch.EnableRaisingEvents = true;

            Console.WriteLine("Press Enter to create a  file.");
            Console.ReadLine();

            if (File.Exists("test.bin")) {
                File.Delete("test.bin");
            }

            // Create test.bin.
            using (FileStream fs = new FileStream("test.bin", FileMode.Create)) {
                // Do something.
            }

            Console.WriteLine("Press Enter to terminate the application.");
            Console.ReadLine();
        }
    }

    private static void OnCreatedOrDeleted(object sender, FileSystemEventArgs e) {
        Console.WriteLine("\tNOTIFICATION: " + e.FullPath + "' was " + e.ChangeType.ToString());
        Console.WriteLine();
    }
}
           
         
    
  








Related examples in the same category

1.Set NotifyFilter of FileSystemWatcher
2.Listens to the file system change notifications and raises events
3.File Watcher