How to get serial number from hard disks?
使用Win32 API获取PC中所有硬盘的序列号有没有简单的方法?
GetVolumeInformation是你的朋友。
GetVolumeInformation
will give you information only about the partition or volume , not about whole HDD.
You should use DeviceIoControl
function to get information.
Here possible code:
#include <atlstr.h>
#include <Windows.h>
#include <winioctl.h>
BOOL getSerial(CString diskSerial) {
BOOL bResult = FALSE;
STORAGE_PROPERTY_QUERY storagePropertyQuery;
STORAGE_DESCRIPTOR_HEADER storageDescHeader = { 0 };
STORAGE_DEVICE_DESCRIPTOR *pDeviceDesc;
DWORD dwBytes = 0;
DWORD dwOutBufferSize = 0;
DWORD dwSerialNumberOffset = 0;
BYTE *pOutBuffer = nullptr;
ZeroMemory(&storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY));
storagePropertyQuery.PropertyId = StorageDeviceProperty;
storagePropertyQuery.QueryType = PropertyStandardQuery;
HANDLE hDevice = CreateFile("\.PhysicalDrive0", 0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
if (hDevice == INVALID_HANDLE_VALUE) {
std::cout << "Can't get access to HDD.nTerminating." << std::endl;
exit(EXIT_FAILURE);
}
bResult = DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&storagePropertyQuery, sizeof(storagePropertyQuery),
&storageDescHeader, sizeof(storageDescHeader),
&dwBytes, NULL);
dwOutBufferSize = storageDescHeader.Size;
try {
pOutBuffer = new BYTE[dwOutBufferSize];
ZeroMemory(pOutBuffer, sizeof(pOutBuffer));
} catch (std::bad_alloc exp) {
CloseHandle(hDevice);
std::cout << exp.what() << std::endl;
return FALSE;
}
bResult = DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
pOutBuffer, dwOutBufferSize, &dwBytes, NULL);
pDeviceDesc = (STORAGE_DEVICE_DESCRIPTOR *)pOutBuffer;
dwSerialNumberOffset = pDeviceDesc->SerialNumberOffset;
diskSerial = CString(pOutBuffer + dwSerialNumberOffset);
std::cout << "Serial Number: " << diskSerial << std::endl;
delete[] pOutBuffer;
CloseHandle(hDevice);
return TRUE;
}
If you have more then 1 hard drives installed, u should change "\.PhysicalDrive0"
to "\.PhysicalDrive1"
etc.
上一篇: 用于桌面的MVC.NET
下一篇: 如何从硬盘获取序列号?