如何获取在Delphi中锁定文件的句柄?

mj2*_*008 4 delphi locking

与LockFile API需要一个文件句柄.我通常使用TStream进行文件访问,所以我不确定如何获得适当的句柄,仅给出一个ANSIString文件名.我的目的是在进程中锁定文件(最初可能不存在),将一些信息写入其他用户,然后解锁并删除它.

我会很感激示例代码或指向它以使其可靠.

RRU*_*RUZ 7

您可以将LockFile函数与CreateFileUnlockFile函数结合使用.

看这个例子

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;
Run Code Online (Sandbox Code Playgroud)

另一个选项是,如果要使用TFileStream锁定文件,可以使用独占访问权限打开文件(fmShareExclusive).

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

end;
Run Code Online (Sandbox Code Playgroud)

注意:在两个示例中,访问都是只读的,您必须更改标志才能写入文件.


Mas*_*ler 6

实际上,它非常简单.TFileStream有一个Handle属性,为您提供该文件的Windows句柄.如果您正在使用其他类型的流,则没有可用的基础文件.