Mirror

Determine if a file is in use (Views: 100)


Problem/Question/Abstract:

I want to do some manipulation in a file and was wondering if there was a function, say IsFileInUse(filename), which will return true if another application/ process is accessing the file at that moment. I need to be able to delete the file and exchange it with another one.

Answer:

Solve 1:

function IsFileInUse(path: string): Boolean;
var
  f: file;
  r: integer;
begin
  r := -1;
  system.AssignFile(f, path);
{$I-}
  reset(f);
{$I+}
  r := ioresult; {sm(ns(r));}
  {5 = access denied}
  if (r = 32) or (r = 5) then
    result := true
  else
    result := false;
  if r = 0 then
    system.close(f);
end;

Solve 2:

A few days ago I was asked how to tell if a given file is already being used by another application. Finding out if a file, given its name, is in use (open), is pretty simple. The process consists in trying to open the file for Exclusive Read/Write access. If the file is already in use, it will be locked (by the calling process) for exclusive access, and the call will fail.

Please note that some application do not lock the file when using it. One clear example of this is NOTEPAD. If you open a TXT file in Notepad, the file will not be locked, so the function below will report the file as not being in use.

The function below, IsFileInUse will return true if the file is locked for exclusive access. As it uses CreateFile, it would also fail if the file doesn't exists. In my opinion, a file that doesn't exist is a file that is not in use. That's why I added the FileExists call in the function. Anyway, here's the function:

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 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  Result := (HFileRes = INVALID_HANDLE_VALUE);
  if not Result then
    CloseHandle(HFileRes);
end;
  
NOTE: The function will return false if the specified file doesn't exist, meaning that it is not in use and can be used for something else.

<< Back to main page