Author: Jonas Bilinkevicius
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:
1 function IsFileInUse(path: string): Boolean;
2 var
3 f: file;
4 r: integer;
5 begin
6 r := -1;
7 system.AssignFile(f, path);
8 {$I-}
9 reset(f);
10 {$I+}
11 r := ioresult; {sm(ns(r));}
12 {5 = access denied}
13 if (r = 32) or (r = 5) then
14 result := true
15 else
16 result := false;
17 if r = 0 then
18 system.close(f);
19 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:
20 function IsFileInUse(fName: string): boolean;
21 var
22 HFileRes: HFILE;
23 begin
24 Result := false;
25 if not FileExists(fName) then
26 exit;
27 HFileRes := CreateFile(pchar(fName), GENERIC_READ or GENERIC_WRITE,
28 0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
29 Result := (HFileRes = INVALID_HANDLE_VALUE);
30 if not Result then
31 CloseHandle(HFileRes);
32 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.
|