我正在尝试查找Windows 7上CDROM驱动器的驱动器号(即,我需要在
我感觉可能错过了关键概念。
以下是我的代码:
\\.\PhysicalDriveN
中找到N
以打开块设备进行读取)。此页面指出,IOCTL_STORAGE_GET_DEVICE_NUMBER应该有效,但对于C:和D:(其中D:是可移动驱动器),它返回0作为驱动器号,因此肯定是不正确的。建议使用IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,但在D:上失败并显示ERROR_INVALID_FUNCTION。我感觉可能错过了关键概念。
以下是我的代码:
#include "stdafx.h"
#include "Windows.h"
void printLastError(){
DWORD lastError;
DWORD bytesReturned;
WCHAR outbuf[2048];
lastError = GetLastError();
bytesReturned = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
NULL, lastError, LANG_USER_DEFAULT, outbuf, 2048, NULL);
if (bytesReturned > 0){
wprintf(outbuf);
} else {
printf("Error %d while formatting error %d\n", GetLastError(), lastError);
}
}
void readDeviceNumberByExtents(HANDLE hFile){
BOOL ioctlSuccess;
DWORD bytesReturned;
VOLUME_DISK_EXTENTS vde;
ioctlSuccess = DeviceIoControl(hFile,
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
NULL, 0, &vde, sizeof(vde), &bytesReturned, NULL);
if (ioctlSuccess != 0){
printf("%d\n", vde.Extents->DiskNumber );
} else {
printLastError();
}
}
void readDeviceNumberByStorage(HANDLE hFile){
BOOL ioctlSuccess;
DWORD bytesReturned;
STORAGE_DEVICE_NUMBER sdn;
ioctlSuccess = DeviceIoControl(hFile,
IOCTL_STORAGE_GET_DEVICE_NUMBER,
NULL, 0, &sdn, sizeof(sdn), &bytesReturned, NULL);
if (ioctlSuccess != 0){
printf("%d\n", sdn.DeviceNumber );
} else {
printLastError();
}
}
void runTest(WCHAR* driveName){
HANDLE driveHandle;
DWORD diskNumber;
driveHandle = CreateFile(driveName,
0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (driveHandle != INVALID_HANDLE_VALUE){
wprintf(L"Opened %s\n", driveName);
printf("Device number by extents: ");
readDeviceNumberByExtents(driveHandle);
printf("Device number by storage: ");
readDeviceNumberByStorage(driveHandle);
CloseHandle(driveHandle);
} else {
printf("Failure!\n");
}
}
int _tmain(int argc, _TCHAR* argv[])
{
runTest(L"\\\\.\\C:");
printf("\n");
runTest(L"\\\\.\\D:");
getc(stdin);
return 0;
}
无论我是以管理员身份运行还是普通用户身份运行,都会得到以下输出:
Opened \\.\C:
Device number by extents: 0
Device number by storage: 0
Opened \\.\D:
Device number by extents: Incorrect function.
Device number by storage: 0