C#通過FileSystemWatcher監控文件添加或者刪除事件

ybny 9年前發布 | 1K 次閱讀 C#

C#通過FileSystemWatcher監控文件添加或者刪除事件,當監控的目錄里的文件增加或者刪除時會觸發指定的事件

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();
}

}</pre>

 本文由用戶 ybny 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!