c++文件监控之FileSystemWatcher
具体代码如下:
#using#include usingnamespacestd; usingnamespaceSystem; usingnamespaceSystem::IO; usingnamespaceSystem::Security::Permissions; publicrefclassWatcher { private: //Definetheeventhandlers. staticvoidOnChanged(Object^/*source*/,FileSystemEventArgs^e) { //Specifywhatisdonewhenafileischanged,created,ordeleted. Console::WriteLine("File:{0}{1}",e->FullPath,e->ChangeType); } staticvoidOnRenamed(Object^/*source*/,RenamedEventArgs^e) { //Specifywhatisdonewhenafileisrenamed. Console::WriteLine("File:{0}renamedto{1}",e->OldFullPath,e->FullPath); } public: [PermissionSet(SecurityAction::Demand,Name="FullTrust")] intstaticrun() { //array ^args=System::Environment::GetCommandLineArgs(); //创建一个FileSystemWatcher并设置它的属性. FileSystemWatcher^fsWatcher=gcnewFileSystemWatcher(); fsWatcher->Path="C:\\files"; /*WatchforchangesinLastAccessandLastWritetimes,and therenamingoffilesordirectories.*/ fsWatcher->NotifyFilter=static_cast (//监听文件的以下属性按需求添加这里我添加了一些常用的 NotifyFilters::LastAccess|//文件或文件夹上一次打开的日期。 NotifyFilters::LastWrite|//上一次向文件或文件夹写入内容的日期 NotifyFilters::FileName|//文件名 NotifyFilters::DirectoryName|//目录名 NotifyFilters::Size);//大小 //监听子目录 fsWatcher->IncludeSubdirectories=true; //Onlywatchtextfiles. //fsWatcher->Filter="*.txt"; //Addeventhandlers. fsWatcher->Changed+=gcnewFileSystemEventHandler(Watcher::OnChanged); fsWatcher->Created+=gcnewFileSystemEventHandler(Watcher::OnChanged); fsWatcher->Deleted+=gcnewFileSystemEventHandler(Watcher::OnChanged); fsWatcher->Renamed+=gcnewRenamedEventHandler(Watcher::OnRenamed); //Beginwatching. fsWatcher->EnableRaisingEvents=true; //Waitfortheusertoquittheprogram. Console::WriteLine("Press\'q\'toquitthesample."); while(Console::Read()!='q'); return0; } }; intmain(){ Watcher::run(); }
过程1.首先创建FileSystemWatcher对象 用来设置一些属性以及添加监听事件
2.设置监听目录
3.设置监听文件的属性
4.设置监听子目录
5.添加监听事件
6.开始监听
上面的sample代码可以在MSDN上找到,如果有不确定的地方,可以查看文档