在 C# 中使用 WMI 查询通过盘符获取硬盘序列号

Obtaining HDD Serial Number via Drive Letter using WMI query in C#

我有以下代码,可以很好地通过 Win32_DiskDrive 中的型号字符串值获取硬盘序列号。但是我需要通过分配的盘符获取序列号。这可能吗?如果有怎么办?

public string GetDriveSerial(string model)
{
    string serial = string.Empty;
    string query = "SELECT * FROM Win32_DiskDrive WHERE Model = '" + model + "'";
    try
    {
        using (var results = new ManagementObjectSearcher("root\CIMV2", query))
        {
            foreach (ManagementObject result in results.Get())
            {
                serial = result["SerialNumber"].ToString();
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    return serial;
}

你可以试试这个:

public static string GetSerialFromDrive(string driveLetter)
{
    try
    {
        using (var partitions = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_LogicalDisk.DeviceID='" + driveLetter +
                                            "'} WHERE ResultClass=Win32_DiskPartition"))
        {
            foreach (var partition in partitions.Get())
            {
                using (var drives = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" +
                                                        partition["DeviceID"] +
                                                        "'} WHERE ResultClass=Win32_DiskDrive"))
                {
                    foreach (var drive in drives.Get())
                    {
                        return (string)drive["SerialNumber"];
                    }
                }
            }
        }
    }
    catch
    {
        return "<unknown>";
    }

    // Not Found
    return "<unknown>";
}

这需要像这样的驱动器号:"C:"、"D:" ... 原代码可见here.