#include <windows.h>
#include <iostream>
// 功能:获取指定物理驱动器的ProductId
std::string GetStorageDeviceProductId(const std::string& drivePath) {
// 打开物理驱动器
HANDLE hDevice = CreateFileA(drivePath.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to open device: " << drivePath << std::endl;
return "";
}
STORAGE_PROPERTY_QUERY query = {};
query.PropertyId = StorageDeviceProperty;
query.QueryType = PropertyStandardQuery;
// 分配足够大的缓冲区来存储STORAGE_DEVICE_DESCRIPTOR及其附加数据
BYTE buffer[1024] = {};
DWORD bytesReturned = 0;
// 查询存储设备属性
BOOL result = DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), &buffer, sizeof(buffer), &bytesReturned, NULL);
if (!result) {
std::cerr << "Failed to query storage device properties." << std::endl;
CloseHandle(hDevice);
return "";
}
// 获取STORAGE_DEVICE_DESCRIPTOR结构
STORAGE_DEVICE_DESCRIPTOR* deviceDescriptor = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(buffer);
// ProductId是一个以NULL结尾的字符串,位于STORAGE_DEVICE_DESCRIPTOR之后
// 确保ProductIdOffset不为0
std::string productId = "";
if (deviceDescriptor->ProductIdOffset != 0) {
productId = reinterpret_cast<const char*>(buffer + deviceDescriptor->ProductIdOffset);
}
CloseHandle(hDevice);
return productId;
}
int main() {
// 示例:获取PhysicalDrive0的ProductId
std::string productId = GetStorageDeviceProductId("\\\\.\\PhysicalDrive0");
std::cout << "ProductId: " << productId << std::endl;
return 0;
}