Search code examples
c#wmidiskunique-id

Diskpart UniqueID - C# how to get that id


I'm familiar with VolumeSerialNumber, i need the Disk ID same as shown in diskpart:

WD My Passport 0740 USB Device Disk ID: 08B29B51 Type : USB Status : Online Path : 0 Target : 0 LUN ID : 0 Location Path : UNAVAILABLE Current Read-only State : No Read-only : No Boot Disk : No Pagefile Disk : No Hibernation File Disk : No Crashdump Disk : No Clustered Disk : No

I can't find anything on the web (WMI) or forums that supports this request. Anybody has an idea?


Solution

  • This is the Method i created for getting DiskID from Driveletter. Probably are better ways to do this, but this worked for me for now. Thanks for all your help.

        public static string GetDiskID(char Drive)
        {
            uint volumeSerialNumber = 0;
            bool DriveFound = false;
            foreach (ManagementObject drive in new ManagementObjectSearcher("select DeviceID, Signature from Win32_DiskDrive").Get())
            {
                foreach (ManagementObject partition in new ManagementObjectSearcher(String.Format("associators of {{Win32_DiskDrive.DeviceID='{0}'}} where AssocClass = Win32_DiskDriveToDiskPartition", drive["DeviceID"])).Get())
                {
                    if (partition != null)
                    {
                        ManagementObject logical = new ManagementObjectSearcher(String.Format("associators of {{Win32_DiskPartition.DeviceID='{0}'}} where AssocClass = Win32_LogicalDiskToPartition", partition["DeviceID"])).First();
                        if (logical != null)
                        {
                            if (logical["Name"] != null)
                            {
                                string logicalName = logical["Name"].ToString();
                                if (logicalName[0] == Drive)
                                {
                                    volumeSerialNumber = (uint)drive["Signature"];
                                    DriveFound = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (DriveFound)
                    break;
            }
             var serial = volumeSerialNumber.ToString("x");
                while (serial.Length < 8)
                {
                    serial = serial.Insert(0, "0");
                }
                return serial.ToUpper();
       }