Get Hard disk serial Number

Joby picture Joby · Nov 3, 2010 · Viewed 101.8k times · Source

I want to get hard disk serial number. How I can I do that? I tried with two code but I am not getting

StringCollection propNames = new StringCollection();
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive");
PropertyDataCollection  props = driveClass.Properties;
foreach (PropertyData driveProperty in props) 
{
    propNames.Add(driveProperty.Name);
}
int idx = 0;
ManagementObjectCollection drives = driveClass.GetInstances();
foreach (ManagementObject drv in drives)
       {
          Label2.Text+=(idx + 1);
          foreach (string strProp in propNames)
           {
            //Label2.Text+=drv[strProp];
         Response.Write(strProp + "   =   " + drv[strProp] + "</br>");
          }
    }

In this one I am not getting any Unique Serial number.
And Second one is

string drive = "C";
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + ":\"");
disk.Get();
Label3.Text = "VolumeSerialNumber="+ disk["VolumeSerialNumber"].ToString();

Here I am getting VolumeSerialNumber. But it is not unique one. If I format the hard disk, this will change. How Can I get this?

Answer

Sprunth picture Sprunth · Nov 3, 2010

Hm, looking at your first set of code, I think you have retrieved (maybe?) the hard drive model. The serial # comes from Win32_PhysicalMedia.

Get Hard Drive model

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

   foreach(ManagementObject wmi_HD in searcher.Get())
   {
    HardDrive hd = new HardDrive();
    hd.Model = wmi_HD["Model"].ToString();
    hd.Type  = wmi_HD["InterfaceType"].ToString(); 
    hdCollection.Add(hd);
   }

Get the Serial Number

 searcher = new
    ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");

   int i = 0;
   foreach(ManagementObject wmi_HD in searcher.Get())
   {
    // get the hard drive from collection
    // using index
    HardDrive hd = (HardDrive)hdCollection[i];

    // get the hardware serial no.
    if (wmi_HD["SerialNumber"] == null)
     hd.SerialNo = "None";
    else
     hd.SerialNo = wmi_HD["SerialNumber"].ToString();

    ++i;
   }

Source

Hope this helps :)