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

bzzcjhmw  于 2024-01-07  发布在  其他
关注(0)|答案(4)|浏览(304)

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

kadbb459

kadbb4591#

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

  1. procedure TFrmMain.Button1Click(Sender: TObject);
  2. var
  3. aHandle : THandle;
  4. aFileSize : Integer;
  5. aFileName : String;
  6. begin
  7. aFileName :='C:\myfolder\myfile.ext';
  8. aHandle := CreateFile(PChar(aFileName),GENERIC_READ, 0, nil, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); // get the handle of the file
  9. try
  10. aFileSize := GetFileSize(aHandle,nil); //get the file size for use in the lockfile function
  11. Win32Check(LockFile(aHandle,0,0,aFileSize,0)); //lock the file
  12. //your code
  13. //
  14. //
  15. //
  16. Win32Check(UnlockFile(aHandle,0,0,aFileSize,0));//unlock the file
  17. finally
  18. CloseHandle(aHandle);//Close the handle of the file.
  19. end;
  20. end;

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

  1. Var
  2. MyStream :TFilestream;
  3. begin
  4. MyStream := TFilestream.Create( aFileName, fmOpenRead or fmShareExclusive );
  5. end;

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

展开查看全部
2exbekwf

2exbekwf2#

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

wlp8pajw

wlp8pajw3#

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

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

字符串

cvxl0en2

cvxl0en24#

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

相关问题