Delphi - finding the process that is accessing a file from my program

前端 未结 3 1504
北恋
北恋 2020-12-14 10:51

I have a Delphi app that regularly writes to a local disk file. Occasionally it is unable to access the file - a sharing violation results when it tries to open it. A retr

3条回答
  •  囚心锁ツ
    2020-12-14 11:13

    Using NtQuerySystemInformation you can list all opened handles by all the processes then you can use this function to get the file name

    function NtQueryInformationFile(FileHandle: THandle;IoStatusBlock: PIO_STATUS_BLOCK; FileInformation: Pointer;Length: DWORD; FileInformationClass: DWORD): NTSTATUS;stdcall; external 'ntdll.dll';
    
    function GetFileNameFromHandle(const hFile: THandle): string;
    var
      IO_STATUSBLOCK:IO_STATUS_BLOCK;
      FileNameInfo:FILE_NAME_INFORMATION;
      szFile:String;
    begin
      FillChar(FileNameInfo.FileName,SizeOf(FileNameInfo.FileName),0);
      NtQueryInformationFile(hFile,@IO_STATUSBLOCK,@FileNameInfo,500,9);
      szFile:=WideCharToString(FileNameInfo.fileName);
      CloseHandle(hFile);
      Result:=szFile;
    end;
    

    If this is your file than raise up a message ...

提交回复
热议问题