Cómo: Supervisar los cambios realizados en el sistema de archivos (C++/CLI)

En el siguiente ejemplo de código se utiliza FileSystemWatcher para registrar los eventos correspondientes a archivos creados, modificados, eliminados o archivos a los que se haya cambiado el nombre.En lugar de tener que sondear periódicamente un directorio para ver si han producido cambios en los archivos, puede utilizar la clase FileSystemWatcher para que se desencadenen eventos cada vez que se detecte un cambio.

Ejemplo

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

Vea también

Referencia

System.IO (Espacio de nombres

Otros recursos

E/S de archivos y secuencias

.NET que programa en Visual C++