void CfileWatcherDlg::watchFile(CString path)
{
HANDLE hDir;
char notify[1024];
DWORD cbBytes,i;
char AnsiChar[3];
wchar_t UnicodeChar[2];
hDir = CreateFile(
path, // pointer to the file name
FILE_LIST_DIRECTORY, // access (read-write) mode
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, // share mode
NULL, // security descriptor
OPEN_EXISTING, // how to create
FILE_FLAG_BACKUP_SEMANTICS, // file attributes
FILE_NOTIFY_INFORMATION *tmp;
if (hDir == INVALID_HANDLE_VALUE)
{
this->m_fileEventInfo.ReplaceSel("hDir:INVALID_HANDLE_VALUE\r\n");
return;
}
if(ReadDirectoryChangesW(hDir, ¬ify, sizeof(notify),
TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_DIR_NAME,
&cbBytes, NULL, NULL))
{
tmp = pnotify;
switch(tmp->Action)
{
case FILE_ACTION_ADDED:
this->m_fileEventInfo.ReplaceSel("Directory/File added (添加文件)- \r\n");
break;
case FILE_ACTION_REMOVED:
this->m_fileEventInfo.ReplaceSel("Directory/File removed (删除文件)- \r\n");
break;
case FILE_ACTION_MODIFIED:
this->m_fileEventInfo.ReplaceSel("Directory/File modified (修改文件内容)- \r\n");
break;
case FILE_ACTION_RENAMED_OLD_NAME:
this->m_fileEventInfo.ReplaceSel("Directory/File old name (修改文件名字)- \r\n");
break;
case FILE_ACTION_RENAMED_NEW_NAME:
this->m_fileEventInfo.ReplaceSel("Directory/File new name - \r\n");
break;
default:
break;
}
}
{
HANDLE hDir;
char notify[1024];
DWORD cbBytes,i;
char AnsiChar[3];
wchar_t UnicodeChar[2];
hDir = CreateFile(
path, // pointer to the file name
FILE_LIST_DIRECTORY, // access (read-write) mode
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, // share mode
NULL, // security descriptor
OPEN_EXISTING, // how to create
FILE_FLAG_BACKUP_SEMANTICS, // file attributes
NULL // file with attributes to copy
);
FILE_NOTIFY_INFORMATION *pnotify=(FILE_NOTIFY_INFORMATION *)notify;FILE_NOTIFY_INFORMATION *tmp;
if (hDir == INVALID_HANDLE_VALUE)
{
this->m_fileEventInfo.ReplaceSel("hDir:INVALID_HANDLE_VALUE\r\n");
return;
}
if(ReadDirectoryChangesW(hDir, ¬ify, sizeof(notify),
TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_DIR_NAME,
&cbBytes, NULL, NULL))
{
tmp = pnotify;
switch(tmp->Action)
{
case FILE_ACTION_ADDED:
this->m_fileEventInfo.ReplaceSel("Directory/File added (添加文件)- \r\n");
break;
case FILE_ACTION_REMOVED:
this->m_fileEventInfo.ReplaceSel("Directory/File removed (删除文件)- \r\n");
break;
case FILE_ACTION_MODIFIED:
this->m_fileEventInfo.ReplaceSel("Directory/File modified (修改文件内容)- \r\n");
break;
case FILE_ACTION_RENAMED_OLD_NAME:
this->m_fileEventInfo.ReplaceSel("Directory/File old name (修改文件名字)- \r\n");
break;
case FILE_ACTION_RENAMED_NEW_NAME:
this->m_fileEventInfo.ReplaceSel("Directory/File new name - \r\n");
break;
default:
break;
}
}
}
使用的vs2010创建MFC工程,没遇到任何问题。
FILE_NOTIFY_INFORMATION结构体中FileName保存变化文件的文件名,不过是Unicode编码的WCHAR型,使用时要转化。