在写一个小程序的时候,只能得到文件的句柄,需要转换成文件路径(包涵了整个文件名的),但是只能在同一个application中使用,夸了不同的application就不行了,下面贴出代码:
第一个function:
const BUFSIZE = 512;
function GetFileNameFromHandle(hFile:THANDLE ):String;
var
pszFilename: array [0..MAX_PATH] of char;
hFileMap: THANDLE;
szTemp: array [0..BUFSIZE - 1] of char;
szName: array [0..MAX_PATH - 1] of char;
// Get the file size.
dwFileSizeHi: DWORD ;
dwFileSizeLo: DWORD;
pMem: Pointer;
szDrive: String;
bFound: BOOL;
P: PChar;
uNameLen: UINT;
szTempFile: String;
begin
Result := ‘‘;
dwFileSizeHi := 0;
dwFileSizeLo := GetFileSize(hFile, @dwFileSizeHi);
if( dwFileSizeLo = 0) and (dwFileSizeHi = 0 ) then begin
ShowMessage(‘Cannot map a file with a length of zero.‘);
Exit;
end;
// Create a file mapping object.
hFileMap := CreateFileMapping(hFile,
Nil,
PAGE_READONLY,
0,
0,
Nil);
if (hFileMap <> 0) then begin
// Create a file mapping to get the file name.
pMem := MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
if (pMem <> NIl) then begin
if (GetMappedFileName (GetCurrentProcess(),
pMem,
PChar(@pszFilename[0]),
MAX_PATH) <> 0) then
begin
// Translate path with device name to drive letters.
szTemp[0] := #0;
if (GetLogicalDriveStrings(BUFSIZE-1, @szTemp[0])) <> 0 then
begin
//szDrive := ‘ :‘#0;
bFound := FALSE;
p := @szTemp[0];
repeat
// Copy the drive letter to the template string
//PChar(szDrive)^ := p^;
szTemp[2] := #0;
szDrive := StrPas(p);
// Look up each device name
fillchar(szName,Length(szName), 0);
if (QueryDosDevice(PChar(szDrive), @szName[0], BUFSIZE) <> 0) then
begin
uNameLen := strlen(@szName[0]);
if (uNameLen < MAX_PATH) then
begin
bFound := strlicomp(@pszFilename[0], @szName[0],
uNameLen) = 0;
if (bFound) then
begin
// Reconstruct pszFilename using szTempFile
// Replace device path with DOS path
szTempFile := format(‘%s%s‘,
[szDrive,
StrPas(PChar(Integer(PChar(@pszFilename[0]))+uNameLen))]);
//StringCchCopyN(pszFilename, MAX_PATH+1, szTempFile, _tcslen(szTempFile));
move(PChar(szTempFile)^, pszFilename, Length(szTempFile)+1);
end;
end;
end;
// Go to the next NULL character.
while (p^<>#0) do Inc(P);
until (bFound or (p^ = #0)); // end of string
end;
end;
UnmapViewOfFile(pMem);
end;
CloseHandle(hFileMap);
end;
Result := String(pszFilename);
end;
另外一个function,也实现了同样的功能:
function GetFileNameFromHandle(hFile : Cardinal) : String;
var
hFileMap : Cardinal;
pMem : Pointer;
FilePath : array [0..MAX_PATH - 1] of Char;
sFilePath : String;
sFileName : String;
begin
Result := ‘‘;
try
hFileMap := CreateFileMapping(hFile, NIL, PAGE_READONLY, 0, 0, NIL);
if hFileMap <> 0 then
begin
pMem := MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
if pMem <> NIL then
begin
if GetMappedFileName(GetCurrentProcess(), pMem,
@FilePath, SizeOf(FilePath)) <> 0 then
begin
sFilePath := StrPas(FilePath);
sFileName := ExtractFileName(sFilePath);
Result := sFilePath;
end else Exit;
end else Exit;
end else Exit;
finally
UnMapViewOfFile(pMem);
CloseHandle(hFileMap);
end; // try...finally
end; // GetFileNameFromHandle