FileInUse function

Giganews Newsgroups
Subject:FileInUse function
Posted by: Patrick Hughes (duhvin…@-RemoveThis-engds.com)
Date:Wed, 31 Mar 2010

function FileInUse(FileName: string): Boolean;
var hFileRes: HFILE;
begin
  Result := False;
  if not FileExists(FileName) then exit;
  hFileRes := CreateFile(PChar(FileName),
                                    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;

I use the FileInUse function to detect if the file in question is in use but i
have found that if the file is opened in simply a "viewer" type of application
such as wordview.exe the function returns false because the file is not opened
for writing.

Any thoughts on how I may improve upon this?

Thank you.

--
Patrick Hughes

Replies