1

We have a client server software that needs to be updated. I need to check if the file is currently being accessed. Is this possible if so how Delphi code if possible. The only place I can see if the file is open is under the shared folders open files. I have tried this code but just shows that the file is not opened.

function TfrmMain.FileInUse(FileName: string): Boolean;

var H_File : HFILE;
begin
  Result := False;

  if not FileExists(FileName) then
    begin
    showmessage ('Doesnt Exist');
    exit;
    end;
  H_File := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0,
    nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

  Result := (H_File = INVALID_HANDLE_VALUE);
  showmessage('Opened');
  if not Result then
    CloseHandle(H_File);
end;
  • What do you mean when you refer to "the file"? – Rob Kennedy Jan 18 '10 at 21:46
  • An exe file that needs to be updated, so I need to make sure that it is not opened before the file is removed and replaced. –  Jan 19 '10 at 12:28
  • @Jason: Maybe you don't have to, after all. You can replace the executable even though it is in use, see http://stackoverflow.com/questions/277514/delphi-how-do-you-auto-update-your-applications/278077#278077 – mghie Jan 19 '10 at 18:10
  • I want to check if the exe is running if so I will kill it then replace the exe. Along with run scripts and a few other things. It needs to make sure that everyone is out of the program. But that link was very helpful thanks. –  Jan 19 '10 at 18:49

3 Answers3

0

There is a great deal of information you can access over the WBEM sub-system provided by Windows. I believe there are good WBEM components out there, but you could also import the "Microsoft WMI Scripting" COM Type Library (though this takes a little work to figure out how it works).

If you query for Win32_ServerConnection objects, you get a list of items currently in use, much like you can view using the 'Computer Management' tool from the Administrative Tools.

Stijn Sanders
  • 35,982
  • 11
  • 45
  • 67
  • I checked out the Win32_ServerConnection objects and it shows how many files are open but not the names of the files. –  Jan 19 '10 at 15:59
0

Not necessarily an answer, but I am currently doing something similar - because the main executable might be updated during working hours though I have created a intermediary application that checks to see if a locally cached copy of the file is up to date, I then run this locally cached copy.

Mark Robinson
  • 943
  • 9
  • 26
0

I found this similar item, someone proposes to use the NetFileEnum function

Community
  • 1
  • 1
Stijn Sanders
  • 35,982
  • 11
  • 45
  • 67