This blog is subject the DISCLAIMER below.

Thursday, June 05, 2008

FileSystemWatcher


FileSystemWatcher Class is very benefit when trying to monitor some files and inform user or program when any change occurs, all events are listed in NotifyFilters enum, this is the list of events can be handled by this:

public enum NotifyFilters {
Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, Size,
}

Now we need to declare functions to be called when some event occurred, this function will run through this delegate:


void MyNotificationHandler(object source, FileSystemEventArgs e)


Only rename event will run through this delegate:

void MyNotificationHandler(object source, RenamedEventArgs e)


Now we will start console application to monitor files, this application will run till user press q, this program will monitor all *.txt files in c:\ folder:


C#:


FileSystemWatcher watcher = new FileSystemWatcher();

// monitor files at:
watcher.Path = @"c:\";

// monitor files when
watcher.NotifyFilter = NotifyFilters.LastAccess NotifyFilters.LastWrite NotifyFilters.FileName NotifyFilters.DirectoryName;

// watch files of type
watcher.Filter = "*.txt";

// watch events:
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEventys = true;

Console.WriteLine("Press 'q' to quit app.");

while (Console.Read() != 'q') ;

vb.net:


Dim watcher As New FileSystemWatcher()


' monitor files at:
watcher.Path = "c:\"

' monitor files when
watcher.NotifyFilter = NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName

' watch files of type
watcher.Filter = "*.txt"

' watch events:
AddHandler watcher.Created, AddressOf OnChanged
AddHandler watcher.Deleted, AddressOf OnChanged

watcher.EnableRaisingEvents = True

Console.WriteLine("Press 'q' to quit app.")

While Console.Read() <> "q"C

End While



As you seen, we call OnChanged function every event occurs, so we can implement this function to print this event and its time like that:


C#:


static void OnChanged(object source, FileSystemEventArgs e)

{

Console.WriteLine("File Changed, File Path: {0} , Change: {1}, DateTime: {2}", e.FullPath, e.ChangeType,DateTime.Now.ToString());

}

vb.net:


Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)

Console.WriteLine("File Changed, File Path: {0} , Change: {1}, DateTime: {2}", e.FullPath, e.ChangeType, DateTime.Now.ToString())

End Sub


Now, this is screen shot of application when delete .txt file and create it again.


No comments: