Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hard drive unique serial number in C#

Tags:

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..

like image 892
JayNaz Avatar asked Apr 27 '15 05:04

JayNaz


2 Answers

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;
   }
like image 102
Rahul Tripathi Avatar answered Nov 12 '22 00:11

Rahul Tripathi


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);
like image 22
Brahim Bourass Avatar answered Nov 11 '22 23:11

Brahim Bourass