Search code examples
wmihard-drive

C# Get a drive's Name via it's Serial ID


I am using C# and working on Visual Studio 2015. I need to get a Connected USB drive's name from it's Serial ID. I tried using WMI Class the query: "SELECT * FROM Win32_LogicalDisk"

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

        foreach (ManagementObject item in searcher.Get())
        {
            if (item != null && item["VolumeSerialNumber"] != null && item["VolumeName"] != null)
            {
                if (item["VolumeSerialNumber"].ToString() == "50D76BF4")
                {
                    Console.WriteLine($"{item["VolumeName"]} Is Connected and It's Letter is {item["Name"]}");
                }
            }          
        }    

However, There VolumeSerialNumber is not ther real Serial ID. It is changed when the disk is formatted.


Solution

  • Ok I figured it out.

    I wrote a method that reutrns a hard drive's name and letter from it's real and unchangable id.

    You need to refernce System.Management

    this is the code:

     public static string GetDriveLetterAndLabelFromID(string id)
        {
             ManagementClass devs = new ManagementClass(@"Win32_Diskdrive");
            {
                ManagementObjectCollection moc = devs.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    string a = (string)mo["SerialNumber"];
                    if (a== id)
                    {
                        foreach (ManagementObject b in
                        mo.GetRelated("Win32_DiskPartition"))
                        {
                            foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
                        {
                            string result = $"HardDrive Name: {c["VolumeName"].ToString()}\nHardDrive Letter: {c["DeviceID"]}";                           
                            return result;
                        }
                        }
                    }
                }
            }
            return null;
        }