3。程序实现
利用上述两个函数,我们可编写程序判断某文件是否正在被其它进程锁定,以下为详细代码。
//利用OpenFile Api函数判断
function FileLocked(Fn: string): Boolean;
var
I : Integer;
Struct: TOfStruct;
Style: Cardinal;
Hdl: Hfile;
Drive: String;
begin
Style := OF_Share_Exclusive; //排它方式打开
Drive := UpperCase(Fn[1]);
Struct.fFixedDisk := Ord(Drive <> 'A'); //判断是否是硬盘
Struct.cBytes := SizeOf(Struct);
For I := 1 to Length(Fn) do
Struct.szPathName[I-1] := Fn[I];
Struct.szPathName[I] := Chr(0); //填充文件名
Hdl := OpenFile(Pchar(Fn), Struct, Style);
if Hdl = HFILE_ERROR then
begin
Result := True; //文件被锁定
Showmessage(SysErrorMessage(GetLastError)); //显示错误原因
end
else
Result := False;
end;
//利用CreateFile Api函数判断
function LockedFile(Fn: string): Boolean;
var
AFile: THandle;
SecAtrrs: TSecurityAttributes;
begin
FillChar(SecAtrrs, SizeOf(SecAtrrs), #0);
SecAtrrs.nLength := SizeOf(SecAtrrs); //结构体长度
SecAtrrs.lpSecurityDescriptor := nil; //安全描述
SecAtrrs.bInheritHandle := True; //继承标志
AFile := CreateFile(PChar(Fn), GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_Read, @SecAtrrs, OPEN_EXISTING,
FILE_ATTRIBUTE_Normal, 0);
if AFile = INVALID_HANDLE_VALUE then
begin
Result := True; //文件被锁定
showmessage(SysErrorMessage(GetLastError));
end
else
Result := False;
end;
4。程序的测试
在Delphi中新建一Application,在Form1的OnCreate事件中写入:
if Not FileLocked(‘c:\windows\desktop\a.txt’) then Showmessage(‘Cannot Open 1’);
或
if Not LockedFile (‘c:\windows\desktop\a.txt’) then Showmessage(‘Cannot Open 2’);
再新建一批处理文件保存到桌面上,内容为:
dir c:\*.*/s>c:\windows\desktop\a.txt’
运行此批处理文件,然后运行上述Delphi程序。这时候会出现消息框“其他进程正使用该文件, 因此现在无法访问。”。当批处理命令运行完毕后,再运行此程序则不会出现此信息。此时,再双击a.txt文档,记事本程序将无法打开该文档,说明加锁成功。
function IsFileInUse(fName : string ) : boolean;
var
HFileRes : HFILE;
begin
Result := false;
if not FileExists(fName) then
exit;
HFileRes := CreateFile(pchar(fName), GENERIC_READ or GENERIC_WRITE,0, nil, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;