...check if a file is in use?

Author: Simon Grossenbacher
Homepage: http://www.swissdelphicenter.ch

Category: Files

function IsFileInUse(FileName: TFileName): 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;


procedure TForm1.Button1Click(Sender: TObject);
begin
  if 
IsFileInUse('c:\Programs\delphi6\bin\delphi32.exe') then
    
ShowMessage('File is in use.');
  else
    
ShowMessage('File not in use.');
end;

 

printed from
www.swissdelphicenter.ch
developers knowledge base