Assuming you still want to do it with WMI: first of all you need some code to read WMI properties in C++. No need to repeat here, you can find it in Getting CPU ID code from C# to be in C++.
When you have that code you can stat to work with disks. First of all you need to remember how Windows organize disks:
- Each physical disk (
Win32_DiskDrive
) is made by partitions (Win32_DiskPartition
).
- Each partition (
Win32_DiskPartition
) is a logical disk (Win32_LogicalDisk
).
- Mapping between each other is done with
Win32_DiskDriveToDiskPartition
and Win32_LogicalDiskToPartition
.
You already know where you're running then you can do this mapping:
Fetch from Win32_LogicalDisk
the one where DeviceID
property matches drive you're running on:
DeviceID=C:
Query Win32_LogicalDiskToPartition
and pick Antecedent
for which Dependent
has ID you previously found:
\\REPETTI\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #1" \\REPETTI\root\cimv2:Win32_LogicalDisk.DeviceID="C:"
Now you should query partitions in Win32_DiskPartition
to find the one where DeviceID
is Disk #1, Partition #1
however also Win32_DiskDriveToDiskPartition
uses DeviceID
for this mapping then you can directly query Win32_DiskDriveToDiskPartition
to match given ID:
\\REPETTI\root\cimv2:Win32_DiskDrive.DeviceID="\\.\PHYSICALDRIVE1" \\REPETTI\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #1"
Now you just need to query Win32_DiskDrive
searching for device ID \\.\PHYSICALDRIVE1
:
WDC WDxxx ATA Device \\.\PHYSICALDRIVE1 WDC WDxxx ATA Device
And you can get its serial number (in this case same property is available both in Win32_PhysicalMedia
and Win32_DiskDrive
otherwise you should search by its Caption
).
Without WMI
If you have to do it without WMI then it's little bit more tricky.
- First of all you need to figure out which physical drive contains your logical drive_ you may follow How to list physical disks?.
- When you have physical drive name easiest way is
CreateFile()
to open drive and get information with DeviceIoControl()
sending S.M.A.R.T. commands. Don't think it's always so easy: with many drives it'll fail and you need administrative rights. Unfortunately there isn't a single perfect solution then you need to try different approaches. AFAIK best and most exhaustive code to handle this is written by Lynn McGuire for its DiskId32 utility.