我一直在尝试使用FileSystemWatcher检测文件夹下载是否已完成的想法。到目前为止我所取得的成就是我能够检测到这个文件夹的创建,然后触发一个监视器,监视这个观察者内部的变化。每当在此文件夹中创建文件时,我将尝试访问它并检查它是否已锁定。
问题是:如何知道此文件夹中的所有文件都已写完?
我知道我可以单独处理每个文件,但是如何从那个文件转到全包结果?
我需要这个,因为在完全写完文件夹之后,我会将其存档,并将其上传到FTP。
这是我现在的代码:
static void OnChanged( Object^ /*source*/, FileSystemEventArgs^ e )
{
Console::WriteLine( "File: {0} {1}", e->FullPath, e->ChangeType );
FileSystemWatcher^ watcher2 = gcnew FileSystemWatcher;
watcher2->Path = e->FullPath;
watcher2->NotifyFilter = static_cast<NotifyFilters>( NotifyFilters::LastWrite | NotifyFilters::DirectoryName |NotifyFilters::FileName);
watcher2->Filter = "*.*";
watcher2->Changed += gcnew FileSystemEventHandler(OnChanged2);
watcher2->EnableRaisingEvents = true;
}
static void OnChanged2(Object^ /*source*/, FileSystemEventArgs^ e )
{
Console::WriteLine( "Watching started", e->FullPath);
FileInfo^ fileInfo = gcnew FileInfo(e->FullPath);
while(IsFileLocked(fileInfo))
{
Thread::Sleep(500);
}
}
static bool IsFileLocked(FileInfo^ file)
{ FileStream ^ stream = nullptr;
try
{
stream = file->Open(System::IO::FileMode::Open,
System::IO::FileAccess::ReadWrite, System::IO::FileShare::None);
}
catch (IOException^ ex)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != nullptr)
stream->Close();
}
//file is not locked
return false;
}
感谢您的帮助!