【问题标题】:C++/CLI: FileSystemWatcher move or copy non empty folderC++/CLI:FileSystemWatcher 移动或复制非空文件夹
【发布时间】:2014-12-26 14:53:58
【问题描述】:

我正在使用 C++/CLI 中的 FileSystemWatcher。我在移动或复制非空文件夹时遇到问题:将包含一个 .txt 文件的文件夹复制到监视文件夹时,会引发多个 createdchanged 事件,这很好,但是当我移动时同一个文件夹,只会引发一个文件夹的创建事件。问题是,我需要知道其中有女巫文件,所以我的想法是在 changed 事件中创建一个循环,以递归方式搜索文件夹。这适用于移动,但是当我复制文件夹时,每个事件都会引发两次。

我找不到算法,因此只引发了一个文件夹和文件的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);
}

【问题讨论】:

    标签: c++ events c++-cli filesystemwatcher


    【解决方案1】:

    我不知道有一种方法可以像您想要的那样只获得一个 Changed 事件。但是,我确实知道如何获取移动文件的事件。您需要附加到 Renamed 事件。

    包含文件的文件夹副本:文件夹一个 Changed 事件,每个文件一个。

    文件夹随文件移动:文件夹一个 Changed 事件,每个文件一个 Renamed 事件。

    【讨论】:

    • 我测试了你所说的,但不幸的是,当我用文件移动文件夹时没有引发 Renamed 事件
    • 是的,你是对的。如果您移动文件本身,您会收到有关文件移动的通知。如果您移动包含文件的目录,则不会收到有关文件的任何通知。
    猜你喜欢
    • 2014-08-15
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    相关资源
    最近更新 更多