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.
source share