2014-12-26 16 views
0

我正在使用C++/CLI中的FileSystemWatcher。移動或複製非空文件夾時遇到問題:將其中包含一個.txt文件的文件夾複製到觀看文件夾時,會引發多個createdchanged事件,這很好,但是當我移動相同的文件夾時,只會引發該文件夾的一個創建事件。問題是,我需要知道巫婆文件,因此我的想法是在changed事件中創建一個循環,遞歸搜索通過文件夾。這適用於移動,但是當我複製文件夾時,每個事件都會產生兩次。C++/CLI:FileSystemWatcher移動或複製非空文件夾

我找不到算法,因此只會引發一個用於文件夾和文件的create事件。

感謝您的幫助。

代碼:

System::Void SnowDrive::Cloud::FileWatcher_Changed(System::Object^ sender, System::IO::FileSystemEventArgs^ e) 
{ 
    size_l FileSize; 

    string ServerInode, 
      FileName = c.marshal_as<std::string> (e -> Name), 
      FilePath = c.marshal_as<std::string> (e -> FullPath), 
      FtpPath = ToFtpPath (FilePath.substr (0, FilePath.find_last_of ("\\"))); 

    if (FileName.find_last_of ("\\") != string::npos) 
     FileName = FileName.substr (FileName.find_last_of ("\\") + 1); 

    for (unsigned int i = 0; i < IgnoreFileList.size(); i++) 
    { 
     if (IgnoreFileList[i] == FilePath) 
     { 
      IgnoreFileList.erase (IgnoreFileList.begin() + i); 

      return; 
     } 
    } 

    if (!FileSystem::IsDir (FilePath)) 
    { 
     FileSystem::FileSize (FilePath, &FileSize); 

     if (FileSize != 0) 
      IgnoreFileList.push_back (FilePath); // ignore twice changed events 

     // do something 
    } 
    else 
    { 
     if (sender -> ToString() != " ") 
      return; 

     DIR * Dir; 

     dirent * FindData; 

     if((Dir = opendir(FilePath.c_str())) == NULL) 
      return; 

     while ((FindData = readdir(Dir)) != NULL) 
     { 
      FileName = FindData -> d_name; 

      if (FileName == string (".") || FileName == string ("..")) 
       continue; 

      FileWatcher_Changed (gcnew String (" "), gcnew IO::FileSystemEventArgs (IO::WatcherChangeTypes::Created, gcnew String (FilePath.c_str()), gcnew String (FileName.c_str()))); 
     } 
    } 
} 

System::Void SnowDrive::Cloud::FileWatcher_Created(System::Object^ sender, System::IO::FileSystemEventArgs^ e) 
{ 
    size_l FileSize; 

    string FilePath = c.marshal_as<std::string> (e -> FullPath); 

    if (!FileSystem::IsDir (FilePath)) 
    { 
     FileSystem::FileSize (FilePath, &FileSize); 

     if (FileSize != 0) 
      IgnoreFileList.push_back (FilePath); // ignore twice changed events 
    } 

    FileWatcher_Changed (gcnew String (" "), e); 
} 

回答

0

我不知道的方式像你想只有一個Changed事件。但是,我確實知道如何爲移動的文件獲取事件。你會想要附加到Renamed事件。

帶文件的文件夾複製:一個文件夾爲Changed事件,每個文件一個。

文件夾隨文件移動:一個文件夾爲Changed事件,一個文件爲Renamed事件。

+0

我測試了你說的內容,但不幸的是,當我用文件移動文件夾時沒有引發更名事件 – schacker22

+0

是的,你是對的。如果您移動文件本身,您會收到文件移動的通知。如果您使用文件移動目錄,則不會收到有關文件的任何通知。 –

相關問題