title | ms.custom | ms.date | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | dev_langs | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How to: Monitor File System Changes (C++/CLI) | Microsoft Docs |
11/04/2016 |
|
article |
|
|
207a3069-e63d-417e-8b56-00ab44f29c52 |
12 |
mikeblome |
mblome |
ghogen |
The following code example uses xref:System.IO.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 xref:System.IO.FileSystemWatcher class to fire events when a change is detected.
// monitor_fs.cpp
// compile with: /clr
#using <system.dll>
using namespace System;
using namespace System::IO;
ref class FSEventHandler
{
public:
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<String^>^ args = Environment::GetCommandLineArgs();
if(args->Length < 2)
{
Console::WriteLine("Usage: Watcher.exe <directory>");
return -1;
}
FileSystemWatcher^ fsWatcher = gcnew FileSystemWatcher( );
fsWatcher->Path = args[1];
fsWatcher->NotifyFilter = static_cast<NotifyFilters>
(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( );
}
System.IO namespace
File and Stream I-O
.NET Programming with C++/CLI (Visual C++)