Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the handle for locking a file in Delphi?

Tags:

locking

delphi

The LockFile API takes a file handle. I normally use TStream for file access, so I'm unsure how to get the appropriate handle, given an ANSIString filename only. My purpose is to lock a file (which may not exist originally) during a process, write some information to other users, and then unlock and delete it.

I would appreciate sample code or pointers to it to make this reliable.

like image 950
mj2008 Avatar asked Dec 06 '22 04:12

mj2008


1 Answers

You can use the LockFile function in conjunction with CreateFile and UnlockFile functions.

See this example

procedure TFrmMain.Button1Click(Sender: TObject);
var
  aHandle     : THandle;
  aFileSize   : Integer;
  aFileName   : String;
begin
    aFileName    :='C:\myfolder\myfile.ext';
    aHandle      := CreateFile(PChar(aFileName),GENERIC_READ, 0, nil, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); // get the handle of the file
    try
        aFileSize   := GetFileSize(aHandle,nil); //get the file size for use in the  lockfile function
        Win32Check(LockFile(aHandle,0,0,aFileSize,0)); //lock the file
        //your code
        //
        //
        //
        Win32Check(UnlockFile(aHandle,0,0,aFileSize,0));//unlock the file
    finally
    CloseHandle(aHandle);//Close the handle of the file.
    end;

end;

Another option , if you want to lock the file using TFileStream you can opening the file using exclusive access (fmShareExclusive).

Var
MyStream :TFilestream;
begin
  MyStream := TFilestream.Create( aFileName, fmOpenRead or fmShareExclusive ); 

end;

Note : in both examples the access is read-only, you must change the flags in order to write the files.

like image 151
RRUZ Avatar answered Jan 11 '23 01:01

RRUZ