tags:

views:

270

answers:

4

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.

+6  A: 

It's pretty simple, actually. TFileStream has a Handle property that gives you the Windows handle to the file. And if you're using some other type of stream, there's no underlying file to work with.

Mason Wheeler
+1  A: 

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.

RRUZ
+3  A: 

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);
skamradt
That isn't quite the same as a lock though is it? And is it safe over a network to a shared drive? I have to be able to guarantee it as much as sensibly possible.
mj2008
Okay, I've read the source, and it does end up at a lock call, so it is good.
mj2008
A: 

Hello, you can find a complete sample to use LockFile API here. It's used to detect computer in use insede a network. It's compiled in Delphi 6 and source is included.

Excuse-me for my bad english.

Regards.

Neftalí