我正在尝试获取物理驱动器的制造商序列号。
我正试图通过这种方式来实现(该代码在HDD上工作得很好,但是返回的序列号不正确,类似这样的0000_0000_0100_0000_E4D2_5C42_46E3_4D01
):
// there I get handle to physical drive
// HANDLE h = CreateFile(L"\\\\.\\PhysicalDrive0", FILE_ANY_ACCESS , FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
// bool success = h != INVALID_HANDLE_VALUE;
std::string getSerialNumber(HANDLE h)
{
std::string result;
static STORAGE_PROPERTY_QUERY spq = { StorageDeviceProperty, PropertyStandardQuery };
union {
PVOID buf;
PSTR psz;
PSTORAGE_DEVICE_DESCRIPTOR psdd;
};
ULONG size = sizeof(STORAGE_DEVICE_DESCRIPTOR) + 0x100;
ULONG dwError;
do
{
dwError = ERROR_NO_SYSTEM_RESOURCES;
if (buf = LocalAlloc(0, size))
{
DWORD returned;
if (DeviceIoControl(h, IOCTL_STORAGE_QUERY_PROPERTY, &spq, sizeof(spq), buf, size, &returned, 0))
{
if (psdd->Version >= sizeof(STORAGE_DEVICE_DESCRIPTOR))
{
if (psdd->Size > size)
{
size = psdd->Size;
dwError = ERROR_MORE_DATA;
}
else
{
if (psdd->SerialNumberOffset)
{
result = psz + psdd->SerialNumberOffset;
dwError = NOERROR;
}
else
{
throw std::runtime_error(std::to_string(ERROR_NO_DATA));
}
}
}
else
{
throw std::runtime_error(std::to_string(ERROR_GEN_FAILURE));
}
}
else
{
throw std::runtime_error(std::to_string(GetLastError()));
}
LocalFree(buf);
}
} while (dwError == ERROR_MORE_DATA);
return result;
}
所以问题是我是否使用API正确的方式?如果有人知道如何以其他方式获取序列号,我将很高兴看到它。
编辑: 我也尝试使用WMI。
Linux和UEFI环境显示正确的结果,在Windows上我无法实现。