How to get a handle to lock a file in Delphi?

The LockFile API accepts a file descriptor. I usually use TStream to access files, so I'm not sure how to get the corresponding descriptor, only with the name ANSIString. My goal is to lock the file (which may not exist initially) during the process, write some information to other users, and then unlock and delete it.

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

+4
source share
4 answers

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

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 open the file using exclusive access (fmShareExclusive).

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

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

+7
source

It is pretty simple, actually. TFileStream has a Handle property that provides a Windows handle to the file. And if you use some other thread, there is no main file to work with.

+6
source

Another option is to create a file stream with exclusive read / write access:

 fMask := fmOpenReadWrite or fmShareExclusive; if not FileExists(Filename) then fMask := fMask or fmCreate; fstm := tFileStream.Create(Filename,fMask); 
+3
source

You can find the full sample for using LockFile API here . It was used to detect a computer on a network on a network. It is compiled in Delphi 6 and the source is included.

Excuse me for my bad english.

Sincerely.

0
source

All Articles