Share via


Using WMI in C# to get Hard disk information that installed Windows ?

Question

Monday, January 21, 2013 9:30 AM

Hi,

I am using below codes to get detail of disk drivers. But, if I have two hard disks, how can I get information of the hard disk that installed Windows OS ?

ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

// Loop through the drives retrieved, although it should normally be only one loop going on here

    foreach (ManagementObject moDisk in mosDisks.Get())
    {

        // Set all the fields to the appropriate values

        lblType.Text = "Type: " + moDisk["MediaType"].ToString();

        lblModel.Text = "Model: " + moDisk["Model"].ToString();

        lblSerial.Text = "Serial: " + moDisk["SerialNumber"].ToString();

        lblInterface.Text = "Interface: " + moDisk["InterfaceType"].ToString();     }

Thanks and regards,

All replies (2)

Monday, January 21, 2013 12:48 PM ✅Answered | 1 vote

With the Win32_OperatingSystem WMI class you can determine the SystemDrive value, which is usually “C:”. Also consider ‘Path.GetPathRoot(Environment.SystemDirectory)’.

Then in order to determine the partition where “C:” is located, use Win32_LogicalDiskToPartition. It will give a partition like “Disk #0, Partition #0”.

To obtain the corresponding Win32_DiskDrive from partition, consider Win32_DiskDriveToDiskPartition.

To check this idea, use the WBEMTest.exe tool that can started manually from Run menu of Windows. The list of all of WMI classes can be found in MSDN.

For querying these associations you have to use ‘ASSOCIATORS OF’. This is an experimental fragment:

string system_disk = Path.GetPathRoot(Environment.SystemDirectory).TrimEnd('\');

using (var m1 = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_LogicalDisk.DeviceID='" + system_disk + "'} WHERE ResultClass=Win32_DiskPartition"))

{

       foreach (var i1 in m1.Get())

       {

              using (var m2 = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + i1["DeviceID"] + "'} WHERE ResultClass=Win32_DiskDrive"))

              {

                     foreach (var i2 in m2.Get())

                     {

                           Console.WriteLine("Type: " + i2["MediaType"]);

                           Console.WriteLine("Model: " + i2["Model"]);

                           break;

                     }

              }

              break;

       }

}


Tuesday, January 22, 2013 8:36 AM

Thanks Viorel,

I think your way is good. But, I resolved this by used below codes:

ManagementClass partionsClass = new ManagementClass("Win32_LogicalDisk");ManagementScope scope = new ManagementScope("root\\CIMV2");
ManagementObjectCollection partions = partionsClass.GetInstances();         

partionsClass.Scope = scope;            

foreach (ManagementObject partion in partions)
{
     strDiskSerial = Convert.ToString(partion["VolumeSerialNumber"]);
     break; }

Kind regards,