c++文件監(jiān)控之FileSystemWatcher
更新時間:2019年04月07日 22:50:10 投稿:mdxy-dxy
為了監(jiān)控web程序的靜態(tài)文件是否被惡意改動,所以學習了一下FileSystemWatcher 類對文件的監(jiān)控,由于還在初級階段,這里只貼一下關(guān)于FileSystemWatcher學習的一些代碼
具體代碼如下:
#using <System.dll>
#include <iostream>
using namespace std;
using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;
public ref class Watcher
{
private:
// Define the event handlers.
static void OnChanged( Object^ /*source*/, FileSystemEventArgs^ e )
{
// Specify what is done when a file is changed, created, or deleted.
Console::WriteLine( "File: {0} {1}", e->FullPath, e->ChangeType );
}
static void OnRenamed( Object^ /*source*/, RenamedEventArgs^ e )
{
// Specify what is done when a file is renamed.
Console::WriteLine( "File: {0} renamed to {1}", e->OldFullPath, e->FullPath );
}
public:
[PermissionSet(SecurityAction::Demand, Name="FullTrust")]
int static run()
{
//array<String^>^args = System::Environment::GetCommandLineArgs();
//創(chuàng)建一個FileSystemWatcher并設(shè)置它的屬性.
FileSystemWatcher^ fsWatcher = gcnew FileSystemWatcher( );
fsWatcher->Path = "C:\\files";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
fsWatcher->NotifyFilter = static_cast<NotifyFilters>(//監(jiān)聽文件的以下屬性 按需求添加 這里我添加了一些常用的
NotifyFilters::LastAccess | //文件或文件夾上一次打開的日期。
NotifyFilters::LastWrite | //上一次向文件或文件夾寫入內(nèi)容的日期
NotifyFilters::FileName | //文件名
NotifyFilters::DirectoryName | //目錄名
NotifyFilters::Size); //大小
//監(jiān)聽子目錄
fsWatcher->IncludeSubdirectories = true;
// Only watch text files.
//fsWatcher->Filter = "*.txt";
// Add event handlers.
fsWatcher->Changed += gcnew FileSystemEventHandler( Watcher::OnChanged );
fsWatcher->Created += gcnew FileSystemEventHandler( Watcher::OnChanged );
fsWatcher->Deleted += gcnew FileSystemEventHandler( Watcher::OnChanged );
fsWatcher->Renamed += gcnew RenamedEventHandler( Watcher::OnRenamed );
// Begin watching.
fsWatcher->EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console::WriteLine( "Press \'q\' to quit the sample." );
while ( Console::Read() != 'q' );
return 0;
}
};
int main() {
Watcher::run();
}
過程 1.首先創(chuàng)建FileSystemWatcher 對象 用來設(shè)置一些屬性以及添加監(jiān)聽事件
2.設(shè)置監(jiān)聽目錄
3.設(shè)置監(jiān)聽文件的屬性
4.設(shè)置監(jiān)聽子目錄
5.添加監(jiān)聽事件
6.開始監(jiān)聽
上面的sample代碼可以在MSDN上找到,如果有不確定的地方,可以查看文檔
相關(guān)文章
詳解C++設(shè)計模式編程中責任鏈模式的應(yīng)用
這篇文章主要介紹了C++設(shè)計模式編程中責任鏈模式的應(yīng)用,責任鏈模式使多個對象都有機會處理請求,從而避免請求的發(fā)送者和接收者之間的耦合關(guān)系,需要的朋友可以參考下2016-03-03
C++ std::Set<std::pair>的實現(xiàn)示例
本文主要介紹了C++ std::Set<std::pair>的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-10-10

