当前位置:编程学习 > Delphi >>

[delphi编程]如何实现监视指定文件夹的文件操作

比如我想监视d:\123\这个文件夹下面是否有创建、修改、读取文件的操作,并且知道是哪个文件被创建,那个文件被修改。
我使用
s1:='d:\123';
H:=FindFirstChangeNotification(Pchar(String(S1)),true,FILE_NOTIFY_CHANGE_FILE_NAME);//监视改文件名tmp:= WaitForSingleObject(H,INFINITE);
while tmp=WAIT_OBJECT_0 do
begin //监视等待
form1.memo1.Lines.Add('有操作')FindNextChangeNotification(h);
tmp:= WaitForSingleObject(H,INFINITE);
end;
只能知道,有没有文件被改名,而不知道哪个文件被改名
我想知道哪个被改。希望高手指点一下
想学习的朋友可以留意,但请不要说话,我会删掉乱发言的人的
补充:感谢雨·林/moon [QQ号26226588]的帮助,问题已解决,下面是完整代码,有不明白的请问雨·林/moon ,嘿嘿,不要让高手浪费了
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

PFileNotifyInformation = ^FILE_NOTIFY_INFORMATION;
FILE_NOTIFY_INFORMATION = Record
NextEntryOffset: DWORD;
Action: DWORD;
FileNameLength: DWORD;
FileName: Array[0..MAX_PATH] Of WideChar;
End;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
hDirectory : LongWord;
pNotify : PFileNotifyInformation;
buffer, strDir: Array[0..1024] Of Char;
dwListBaseLength, BytesReturned: integer;
begin
New( pNotify );
Fillchar( buffer ,SizeOf( buffer ), #0 );
StrMove( buffer, @pNotify , sizeof( pNotify ) );

lstrcpy( strDir, 'd:\web' );
Fillchar( pNotify.FileName , MAX_PATH, #0 );
hDirectory := CreateFile( strDir, GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE,
nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0
);

dwListBaseLength := sizeof( FILE_NOTIFY_INFORMATION ) + MAX_PATH;

ReadDirectoryChangesW( hDirectory, pNotify, dwListBaseLength,
true, FILE_NOTIFY_CHANGE_FILE_NAME, @BytesReturned, nil, nil );
ShowMessage( WideCharToString( pNotify.FileName ) );
end;
end.
答案:
建议不要用FindNextChangeNotification,因为确实不清楚如何获得改变了的文件名,API的话可以使用ReadDirectoryChangesW来完成这个任务(当然还有一个也很好的API SHChangeNotifyRegister)。驱动层的监视更为好,不过这里我就不谈了。

char *strDir = "k:/temp/Other";

HANDLE hDirectory;
hDirectory = CreateFile( strDir, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL
);

const unsigned int dwListBaseLength = sizeof( FILE_NOTIFY_INFORMATION ) + MAX_PATH;

char buffer[ dwListBaseLength ] = { 0 };
FILE_NOTIFY_INFORMATION *pNotify = (FILE_NOTIFY_INFORMATION *) buffer;
DWORD BytesReturned = 0;

ReadDirectoryChangesW( hDirectory, pNotify, sizeof(buffer),
true, FILE_NOTIFY_CHANGE_FILE_NAME, &BytesReturned, NULL, NULL );

ShowMessage( WideCharToString( pNotify->FileName ) );


我是用bcb写的,你将她转为delphi就行了。
这个问题太难了,真是爱莫能助呀。哎。。。

上一个:菜鸟delphi编程~~~高手帮帮
下一个:DelPhi编程中session是做什么的变量?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,