监视各进程对指定目录及子目录下的文件的访问

Fnems 2005-02-08 04:12:46
我想写代码监视各进程对指定目录及子目录下的文件的访问,
请给出思路和简单代码举例

    谢谢!
...全文
329 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
Fnems 2005-02-12
  • 打赏
  • 举报
回复
还是提示 '打开文件夹失败!' ,可能是我的OS的问题。

谢谢各位,特别是Eastunfail的帮助!
wfhlxl 2005-02-11
  • 打赏
  • 举报
回复
SHChangeNotifyRegister Function

--------------------------------------------------------------------------------

Registers a window that receives notifications from the file system or shell.

Syntax

ULONG SHChangeNotifyRegister( HWND hwnd,
int fSources,
LONG fEvents,
UINT wMsg,
int cEntries,
SHChangeNotifyEntry *pfsne
);
Parameters

hwnd
Handle to the window that receives the change or notification messages.
fSources
One or more of the following flags that indicates the type of events for which to receive notifications.
SHCNRF_InterruptLevel
Interrupt level notifications from the file system.
SHCNRF_ShellLevel
Shell level notifications from the shell.
SHCNRF_RecursiveInterrupt
Interrupt events on the whole subtree. This flag must be combined with the SHCNRF_InterruptLevel flag. When using this flag, notifications must also be made recursive by setting the fRecursive member of the corresponding SHChangeNotifyEntry structure referenced by pfsne to TRUE.
SHCNRF_NewDelivery
Messages received use shared memory. Call SHChangeNotification_Lock to access the actual data. Call SHChangeNotification_Unlock to release the memory when done.
fEvents
Change notification events for which to receive notification.
wMsg
Message to be posted to the window procedure.
cEntries
Number of entries in the pfsne array.
pfsne
Array of SHChangeNotifyEntry structures that contain the notifications. This array should always be set to one when calling SHChangeNotifyRegister or SHChangeNotifyDeregister will not work properly.
Return Value

Returns a positive integer registration identifier (ID). Returns zero if out of memory or in response to invalid parameters.

Remarks

When a relevant file system event takes place and the hwnd parameter is not NULL, then the message indicated by wMsg is posted to the specified window. Otherwise, if the pfsne parameter is not NULL, then that notification entry is called.

Eastunfail 2005-02-11
  • 打赏
  • 举报
回复
我这里测试成功啊

hDirectory:=CreateFile(PChar(Directory),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,0);
应该改为
hDirectory:=CreateFile(PChar(Directory),GENERIC_READ,FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE,nil,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,0);
Fnems 2005-02-11
  • 打赏
  • 举报
回复
代码执行不成功,每次都在
if hDirectory=INVALID_HANDLE_VALUE then
处被截住提示 '打开文件夹失败!'
Eastunfail 2005-02-10
  • 打赏
  • 举报
回复
program TestConsole;

{$APPTYPE CONSOLE}

uses
SysUtils,Windows;

type
PFileNotifyInformation=^TFileNotifyInformation;
TFileNotifyInformation=packed record
NextEntryOffset:DWORD;
Action:DWORD;
FileNameLength:DWORD;
FileName:array[0..1] of WideChar;
end;

const FileActions:array[FILE_ACTION_ADDED..FILE_ACTION_RENAMED_NEW_NAME] of string
=('添加','删除','修改','改名'{FileName为改名前的新名字},'改名'{FileName为改名后的新名字});
var Notify:PFileNotifyInformation;
Buffer:array[1..5000] of char;
hDirectory:THandle;
BytesReturned:DWORD;
Directory:String;
begin
{ TODO -oUser -cConsole Main : Insert code here }
Write('输入你要监视的目录:');
Readln(Directory);
if not DirectoryExists(Directory) then
begin
Writeln('该目录不存在!');
halt;
end;


hDirectory:=CreateFile(PChar(Directory),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,0);
if hDirectory=INVALID_HANDLE_VALUE then
begin
Writeln('打开文件夹失败!');
halt;
end;//if
while true do
begin
if ReadDirectoryChanges(hDirectory,@Buffer[1],sizeof(Buffer),true,
FILE_NOTIFY_CHANGE_ATTRIBUTES or FILE_NOTIFY_CHANGE_FILE_NAME or
FILE_NOTIFY_CHANGE_DIR_NAME or FILE_NOTIFY_CHANGE_SIZE or
FILE_NOTIFY_CHANGE_LAST_WRITE or FILE_NOTIFY_CHANGE_LAST_ACCESS or
FILE_NOTIFY_CHANGE_CREATION or FILE_NOTIFY_CHANGE_SECURITY,
@BytesReturned,nil,nil) then
begin
Notify:=@Buffer[1];
repeat
Write(Format('[%s]文件名: %s'#13#10,[
FileActions[Notify.Action],WideString(@Notify.FileName[0])
]));
Inc(Notify,Notify.NextEntryOffset );
until Notify.NextEntryOffset =0;
end;//if
end;//while

end.
Fnems 2005-02-10
  • 打赏
  • 举报
回复
谢谢!  准备结贴。

能否再耽误些时间,给出示例代码?比如监视document下的file.txt访问情况?要求只要进行访问,读取或属性修改,就能记下访问时间和用户(最好还有进程ID) Thanks!
Eastunfail 2005-02-09
  • 打赏
  • 举报
回复
MSDN Home > MSDN Library > Win32 and COM Development > System Services > Files and I/O > Storage > Storage Reference > Directory Management Reference > Directory Management Functions

Platform SDK: Storage
FindFirstChangeNotification

The FindFirstChangeNotification function creates a change notification handle and sets up initial change notification filter conditions. A wait on a notification handle succeeds when a change matching the filter conditions occurs in the specified directory or subtree. However, the function does not indicate the change that satisfied the wait condition.

To retrieve information about the specific change as part of the notification, use the ReadDirectoryChangesW function.

HANDLE FindFirstChangeNotification(
LPCTSTR lpPathName,
BOOL bWatchSubtree,
DWORD dwNotifyFilter
);

Parameters

lpPathName
[in] Pointer to a null-terminated string that specifies the path of the directory to watch.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

Windows Me/98/95: This string must not exceed MAX_PATH characters.

bWatchSubtree
[in] Specifies whether the function will monitor the directory or the directory tree. If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory; if it is FALSE, it monitors only the specified directory.
dwNotifyFilter
[in] Filter conditions that satisfy a change notification wait. This parameter can be one or more of the following values.
Value Meaning
FILE_NOTIFY_CHANGE_FILE_NAME Any file name change in the watched directory or subtree causes a change notification wait operation to return. Changes include renaming, creating, or deleting a file name.
FILE_NOTIFY_CHANGE_DIR_NAME Any directory-name change in the watched directory or subtree causes a change notification wait operation to return. Changes include creating or deleting a directory.
FILE_NOTIFY_CHANGE_ATTRIBUTES Any attribute change in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_SIZE Any file-size change in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change in file size only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_WRITE Any change to the last write-time of files in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change to the last write-time only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_SECURITY Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return.

Return Values

If the function succeeds, the return value is a handle to a find change notification object.

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

If the network redirector or the target file system does not support this operation, the function fails with ERROR_INVALID_FUNCTION.
Remarks

The wait functions can monitor the specified directory or subtree by using the handle returned by the FindFirstChangeNotification function. A wait is satisfied when one of the filter conditions occurs in the monitored directory or subtree.

After the wait has been satisfied, the application can respond to this condition and continue monitoring the directory by calling the FindNextChangeNotification function and the appropriate wait function. When the handle is no longer needed, it can be closed by using the FindCloseChangeNotification function.
Example Code

For an example, see Obtaining Directory Change_Notifications.
Requirements
Client Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header

Declared in Winbase.h; include Windows.h.
Library

Link to Kernel32.lib.
DLL Requires Kernel32.dll.
Unicode

Implemented as FindFirstChangeNotificationW (Unicode) and FindFirstChangeNotificationA (ANSI). Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.
See Also

Directory Management Functions, FindCloseChangeNotification, FindNextChangeNotification, ReadDirectoryChangesW

Last updated: January 2005 | What did you think of this topic? | Order a Platform SDK CD
© 2005 Microsoft Corporation. All rights reserved. Terms of use.

Eastunfail 2005-02-09
  • 打赏
  • 举报
回复

Return Values

If the function succeeds, the return value is nonzero. For synchronous calls, this means that the operation succeeded. For asynchronous calls, this indicates that the operation was successfully queued.

If the function fails, the return value is zero (0). To get extended error information, call GetLastError.

If the network redirector or the target file system does not support this operation, the function fails with ERROR_INVALID_FUNCTION.
Remarks

To obtain a handle to a directory, use the CreateFile function with FILE_FLAG_BACKUP_SEMANTICS. For an example, see Obtaining a Handle to a Directory.

A call to ReadDirectoryChangesW can be completed synchronously or asynchronously. To specify asynchronous completion, open the directory with CreateFile as shown above, but additionally specify the FILE_FLAG_OVERLAPPED attribute in the dwFlagsAndAttributes parameter. Then specify an OVERLAPPED structure when you call ReadDirectoryChangesW.

When you first call ReadDirectoryChangesW, the system allocates a buffer to store change information. This buffer is associated with the directory handle until it is closed and its size does not change during its lifetime. Directory changes that occur between calls to this function are added to the buffer and then returned with the next call. If the buffer overflows, the changes are discarded and the function fails with ERROR_NOTIFY_ENUM_DIR.

Upon successful synchronous completion, the lpBuffer parameter is a formatted buffer and the number of bytes written to the buffer is available in lpBytesReturned. If the number of bytes transferred is zero (0), the buffer was too small to provide detailed information on all the changes that occurred in the directory or subtree. In this case, you should compute the changes by enumerating the directory or subtree.

For asynchronous completion, you can receive notification in one of three ways:

* Using the GetOverlappedResult function. To receive notification through GetOverlappedResult, do not specify a completion routine in the lpCompletionRoutine parameter. Be sure to set the hEvent member of the OVERLAPPED structure to a unique event.
* Using the GetQueuedCompletionStatus function. To receive notification through GetQueuedCompletionStatus, do not specify a completion routine in lpCompletionRoutine. Associate the directory handle hDirectory with a completion port by calling the CreateIoCompletionPort function.
* Using a completion routine. To receive notification through a completion routine, do not associate the directory with a completion port. Specify a completion routine in lpCompletionRoutine. This routine is called whenever the operation has been completed or canceled while the thread is in an alertable wait state. The hEvent member of the OVERLAPPED structure is not used by the system, so you can use it yourself.

ReadDirectoryChangesW fails with ERROR_INVALID_PARAMETER when the buffer length is greater than 64 KB and the application is monitoring a directory over the network. This is due to a packet size limitation with the underlying file sharing protocols.

Windows NT 4.0: The limit in this situation is 4 KB.

Windows 2000: Clients that attempt multiple simultaneous long-term requests against a server, for example change notifications, should be running Service Pack 2 or higher. See Knowledge Base article Q271148 for more details.

Windows Me: There is similar functionality available with the FindFirstChangeNotification function.

To compile an application that uses this function, define the _WIN32_WINNT macro as 0x0400 or later. For more information, see Using the Windows Headers.
Requirements
Client Requires Windows XP, Windows 2000 Professional, or Windows NT Workstation 4.0.
Server Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server 4.0.
Header

Declared in Winbase.h; include Windows.h.
Library

Link to Kernel32.lib.
DLL Requires Kernel32.dll.
See Also

CreateFile, CreateIoCompletionPort, Directory Management Functions, FileIOCompletionRoutine, GetOverlappedResult, GetQueuedCompletionStatus, FILE_NOTIFY_INFORMATION, OVERLAPPED

Last updated: January 2005 | What did you think of this topic? | Order a Platform SDK CD
© 2005 Microsoft Corporation. All rights reserved. Terms of use.



Manage Your Profile |Legal |Contact Us |MSDN Flash Newsletter
©2005 Microsoft Corporation. All rights reserved. Terms of Use |Trademarks |Privacy Statement
Microsoft
Eastunfail 2005-02-09
  • 打赏
  • 举报
回复

MSDN Home > MSDN Library > Win32 and COM Development > System Services > Files and I/O > Storage > Storage Reference > Directory Management Reference > Directory Management Functions

Platform SDK: Storage
ReadDirectoryChangesW

The ReadDirectoryChangesW function retrieves information that describes the changes within a directory.

To track changes on a volume, see change journals.

BOOL ReadDirectoryChangesW(
HANDLE hDirectory,
LPVOID lpBuffer,
DWORD nBufferLength,
BOOL bWatchSubtree,
DWORD dwNotifyFilter,
LPDWORD lpBytesReturned,
LPOVERLAPPED lpOverlapped,
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

Parameters

hDirectory
[in] The handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right.
lpBuffer
[in, out] The pointer to the formatted buffer in which the read results are to be returned. The structure of this buffer is defined by the FILE_NOTIFY_INFORMATION structure. This buffer is filled either synchronously or asynchronously, depending on how the directory is opened and what value is given to the lpOverlapped parameter. For more information, see the Remarks section.
nBufferLength
[in] The length of the buffer that is pointed to by the lpBuffer parameter, in bytes.
bWatchSubtree
[in] If this parameter is TRUE, the function monitors the directory tree rooted at the specified directory. If this parameter is FALSE, the function monitors only the directory specified by the hDirectory parameter.
dwNotifyFilter
[in] The filter criteria that the function checks to determine if the wait operation has completed. This parameter can be one or more of the following values.
Value Meaning
FILE_NOTIFY_CHANGE_FILE_NAME Any file name change in the watched directory or subtree causes a change notification wait operation to return. Changes include renaming, creating, or deleting a file.
FILE_NOTIFY_CHANGE_DIR_NAME Any directory-name change in the watched directory or subtree causes a change notification wait operation to return. Changes include creating or deleting a directory.
FILE_NOTIFY_CHANGE_ATTRIBUTES Any attribute change in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_SIZE Any file-size change in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change in file size only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_WRITE Any change to the last write-time of files in the watched directory or subtree causes a change notification wait operation to return. The operating system detects a change to the last write-time only when the file is written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is sufficiently flushed.
FILE_NOTIFY_CHANGE_LAST_ACCESS Any change to the last access time of files in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_CREATION Any change to the creation time of files in the watched directory or subtree causes a change notification wait operation to return.
FILE_NOTIFY_CHANGE_SECURITY Any security-descriptor change in the watched directory or subtree causes a change notification wait operation to return.
lpBytesReturned
[out] For synchronous calls, this parameter receives the number of bytes transferred into the lpBuffer parameter. For asynchronous calls, this parameter is undefined. You must use an asynchronous notification technique to retrieve the number of bytes transferred.
lpOverlapped
[in] The pointer to an OVERLAPPED structure that supplies data to be used during asynchronous operation. Otherwise, this value is NULL. The Offset and OffsetHigh members of this structure are not used.
lpCompletionRoutine
[in] The pointer to a completion routine to be called when the operation has been completed or canceled and the calling thread is in an alertable wait state. For more information about this completion routine, see FileIOCompletionRoutine.
Fnems 2005-02-09
  • 打赏
  • 举报
回复
找不到网页
您要查看的网页可能已被删除、名称已被更改,或者暂时不可用。

--------------------------------------------------------------------------------

请尝试以下操作:

如果您已经在地址栏中输入该网页的地址,请确认其拼写正确。

打开 msdn.microsoft.com 主页,然后查找指向您感兴趣信息的链接。
单击后退按钮,尝试其他链接。
单击搜索,寻找 Internet 上的信息。



HTTP 404 - 未找到文件
Internet Explorer

------------------------------------------------------------------------

能转贴一下么? 或发送到 flbq#163.net
谢谢
Eastunfail 2005-02-09
  • 打赏
  • 举报
回复
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/findfirstchangenotification.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/base/readdirectorychangesw.asp
Fnems 2005-02-09
  • 打赏
  • 举报
回复

我试过了,只能监视外壳的文件操作,而对于其他进程,程序只提示“未知操作”,不符合要求。
另外,那个程序也不能监视文件读取,不符合要求 ;-)

TechnoFantasy 2005-02-08
  • 打赏
  • 举报
回复
Delphi实现的:

http://dev.csdn.net/article/3/3545.shtm
TechnoFantasy 2005-02-08
  • 打赏
  • 举报
回复
介绍如何利用Windows未公开函数实现系统文件操作监视功能


http://www.applevb.com/art/undoc3.htm

1,183

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧