Udostępnij za pośrednictwem


Jak: monitorowanie zmian systemu plików (C + +/ CLI)

Następujący kod w przykładzie wykorzystano FileSystemWatcher do rejestrowania zdarzeń odpowiadające plików tworzonych zmienionych, usunięte lub zmieniono nazwę.Zamiast okresowego sondowania katalog dla zmian plików, można użyć FileSystemWatcher klasy zdarzeń po wykryciu zmiany ognia.

Przykład

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

Zobacz też

Informacje

Obszar nazw System.IO

Inne zasoby

Plik i strumień we/wy

.NET Programowanie w języku Visual C++