Friday, November 7, 2008

How to: Monitor File System Changes

How to: Monitor File System Changes

The following code example uses FileSystemWatcher to register for events corresponding to files being created, changed, deleted, or renamed. Instead of periodically polling a directory for changes to files, you can use the FileSystemWatcher class to fire events when a change is detected.
Copy Code

// monitor_fs.cpp
// compile with: /clr

using namespace System;
using namespace System::IO;

ref class FSEventHandler
void OnChanged (Object^ source, FileSystemEventArgs^ e)
Console::WriteLine("File: {0} {1}",
e->FullPath, e->ChangeType);
void OnRenamed(Object^ source, RenamedEventArgs^ e)
Console::WriteLine("File: {0} renamed to {1}",
e->OldFullPath, e->FullPath);

int main()
array^ args = Environment::GetCommandLineArgs();

if(args->Length < 2)
Console::WriteLine("Usage: Watcher.exe ");
return -1;

FileSystemWatcher^ fsWatcher = gcnew FileSystemWatcher( );
fsWatcher->Path = args[1];
fsWatcher->NotifyFilter = static_cast
(NotifyFilters::FileName |
NotifyFilters::Attributes |
NotifyFilters::LastAccess |
NotifyFilters::LastWrite |
NotifyFilters::Security |
NotifyFilters::Size );

FSEventHandler^ handler = gcnew FSEventHandler();
fsWatcher->Changed += gcnew FileSystemEventHandler(
handler, &FSEventHandler::OnChanged);
fsWatcher->Created += gcnew FileSystemEventHandler(
handler, &FSEventHandler::OnChanged);
fsWatcher->Deleted += gcnew FileSystemEventHandler(
handler, &FSEventHandler::OnChanged);
fsWatcher->Renamed += gcnew RenamedEventHandler(
handler, &FSEventHandler::OnRenamed);

fsWatcher->EnableRaisingEvents = true;

Console::WriteLine("Press Enter to quit the sample.");
Console::ReadLine( );

See Also
System.IO namespace
Other Resources
File and Stream I/O
.NET Programming in C++

No comments: