通过文件句柄取得到文件名

用的是wdk函数ZwQueryObject()。

LPWSTR GetFileNameFromHandleW(HANDLE hFile, LPWSTR lpFilePath) { const int ObjectNameInformation = 1; // enum OBJECT_INFORMATION_CLASS; typedef LONG (CALLBACK* ZWQUERYOBJECT)( HANDLE ObjectHandle, ULONG ObjectInformationClass, PVOID ObjectInformation, ULONG ObjectInformationLength, PULONG ReturnLength ); lpFilePath[0] = 0x00; HMODULE hNtDLL = LoadLibraryW(L"ntdll.dll"); if (hNtDLL == 0x00) { return 0x00; } ZWQUERYOBJECT ZwQueryObject = (ZWQUERYOBJECT)GetProcAddress(hNtDLL, "ZwQueryObject"); if (ZwQueryObject == 0x00) { return 0x00; } WCHAR szPathInfo[MAX_PATH + 4]; WCHAR szDrive [MAX_PATH]; WCHAR *lpDrive = szDrive; ULONG dwResult; int iPathLen; if (ZwQueryObject(hFile, ObjectNameInformation, szPathInfo, sizeof(szPathInfo)-1 , &dwResult) != 0) { return 0x00; } // if the file on net drive const PWCHAR szNetDevice = L"//Device//LanmanRedirector"; if (!wcsnicmp(szPathInfo + 4, szNetDevice, lstrlenW(szNetDevice))) { lstrcpyW(lpFilePath, L"//"); lstrcatW(lpFilePath, szPathInfo + 4 + lstrlenW(szNetDevice)); return lpFilePath; } if (GetLogicalDriveStringsW(MAX_PATH-1, szDrive) >= MAX_PATH) { return 0x00; } while ((iPathLen = lstrlenW(lpDrive)) != 0) { WCHAR szDevName[MAX_PATH]; lpDrive[iPathLen - 1] = 0x00; int iDevLen = (int)QueryDosDeviceW(lpDrive, szDevName, MAX_PATH); if (iDevLen && iDevLen < MAX_PATH){ iDevLen = lstrlenW(szDevName); if (!wcsnicmp(szPathInfo + 4, szDevName, iDevLen)) { lstrcpyW(lpFilePath, lpDrive); lstrcatW(lpFilePath, szPathInfo + 4 + iDevLen); break; } } lpDrive += iPathLen + 1; } return lpFilePath; }   

 

以上方法只能取得本地磁盘或网络上的文件名。一些特殊的比如说从 CreateFile("////.//COM1",GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);之类的句柄就无法取得了。

你可能感兴趣的:(object,File,Class,Path,callback,磁盘)