I need to get the serial numbers of various storage devices. At the moment, the code is written correctly working with the HDD, but when working with SSD, the function returns the wrong result ( 0000_0000_0100_0000_E4D2_5C42_46E3_4D01 ), which I expect.
Also tried using WMI, the result is the same.
The question is: do I use this code correctly when applied to SSD. Is there any other solutions? Feel free to write.
// 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; } I tried to get this serial number from Linux and UEFI - the result is the same, the number is displayed correctly.
I also tried to obtain this GUI serial number using Windows tools — I could not find a solution (but I need to get the number programmatically).
wmic diskdrive get model,name,serialnumberWD10JPVX-22JC3T0 \\. \ PHYSICALDRIVE1 WD-WXP1A560K457 serialwmic diskdrive get model,name,serialnumberWDC WD10JPVX-22JC3T0. Your code issues "WD-WXP1A560K457". Superfluous gaps, but I think it is not critical. - goldstar_labs