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

bzzcjhmw  于 9个月前  发布在  其他
关注(0)|答案(4)|浏览(170)

LockFile API获取一个文件句柄。我通常使用TStream访问文件,所以我不确定如何获取适当的句柄,只给出一个ANSIString文件名。我的目的是在进程中锁定一个文件(最初可能不存在),向其他用户写入一些信息,然后解锁并删除它。
我将感谢样本代码或指针,使这可靠。

kadbb459

kadbb4591#

您可以将LockFile功能与CreateFile和**UnlockFile**功能结合使用。
查看此示例

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;

字符串
另一个选项,如果你想使用TFileStream锁定文件,你可以使用独占访问(fmShareExclusive)打开文件。

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

end;

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

2exbekwf

2exbekwf2#

事实上,这很简单。TFileStream有一个Handle属性,它为您提供文件的Windows句柄。如果您使用其他类型的流,则没有基础文件可供使用。

wlp8pajw

wlp8pajw3#

另一种选择是创建具有独占读/写访问权限的文件流:

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

字符串

cvxl0en2

cvxl0en24#

你可以找到一个完整的例子来使用LockFileAPI here。它被用来检测在网络中使用的计算机。它是在 Delphi 6中编译的,并包括源代码。
请原谅我英语不好。
祝你好运

相关问题