Use FileSystemWatcher to detect file changes in CSharp

Description

The following code shows how to use FileSystemWatcher to detect file changes.

Example


/*from   w  ww . j  a  v a  2s  . c o  m*/
using System;
using System.IO;
using System.Windows.Forms;

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

            watch.Created += new FileSystemEventHandler(OnCreatedOrDeleted);
            watch.Deleted += new FileSystemEventHandler(OnCreatedOrDeleted);
            watch.EnableRaisingEvents = true;

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

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

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




















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip