CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 385

385

Chương 9: File, thư mục, và I/O

Thuộc tính

NotifyFilter

có thể được thiết lập bằng cách kết hợp các giá trị thuộc kiểu liệt kê

System.IO.NotifyFilters

:

Attributes

,

CreationTime

,

DirectoryName

,

FileName

,

LastWrite

,

LastAccess

,

Security

, và

Size

.

Ví dụ dưới đây thụ lý sự kiện

Created

Deleted

. Và thử nghiệm các sự kiện này bằng cách

tạo ra một file thử nghiệm.

using System;

using System.IO;

using System.Windows.Forms;

public class FileWatcherTest {

private static void Main() {

// Cấu hình FileSystemWatcher.

FileSystemWatcher watch = new FileSystemWatcher();

watch.Path = Application.StartupPath;

watch.Filter = "*.*";

watch.IncludeSubdirectories = true;

// Đăng ký các phương thức thụ lý sự kiện.

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");

}

FileStream fs = new FileStream("test.bin", FileMode.Create);

fs.Close();

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

Console.WriteLine();

Console.ReadLine();

}