JayNaz
JayNaz

Reputation: 363

How to get hard drive unique serial number in C#

I develop an activation for a system. to generate request code, I used HDD ID, Bios ID and Processor ID. I used following code to get hard disk ID.

private string getHardDiskID()
{
     string hddID = null;
     ManagementClass mc = new ManagementClass("Win32_LogicalDisk");
     ManagementObjectCollection moc = mc.GetInstances();
     foreach (ManagementObject strt in moc)
     {
         hddID += Convert.ToString(strt["VolumeSerialNumber"]);
     }
     return hddID.Trim().ToString();
}

But if I plug a removable disk, That ID value is changed. How to get the UNIQUE Serial Number of the hard drive...? Thanks in advance..

Upvotes: 6

Views: 15852

Answers (3)

Brahim Bourass
Brahim Bourass

Reputation: 149

ManagementObjectSearcher searcher;

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

        foreach (ManagementObject wmi_HD in searcher.Get())
        {

             serial_number = wmi_HD["SerialNumber"].ToString();


        }

        MessageBox.Show(serial_number);

Upvotes: 2

Rahul Nikate
Rahul Nikate

Reputation: 6337

Check below code to get HDD Serial

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

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

   int i = 0;

   foreach(ManagementObject wmi_HD in objSearcher.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;

   }

Also You can type "wbemtest" in windows run. WBEMTEST is tool which helps in running WQL queries.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

You can try from this source:

As said in the source, a better solution is to get the Hard Drive Serial Number given by the Manufacturer. This value won't change even if you format your Hard Drive.

 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;
   }

Upvotes: 3

Related Questions