简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM