使用C#中的WMI查询通过驱动器号获取HDD序列号

时间:2015-06-30 05:09:12

标签: c# wmi hard-drive

我有以下代码,可以通过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;
}

1 个答案:

答案 0 :(得分:5)

你可以试试这个:

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

这需要这样的驱动器号:&#34; C:&#34;,&#34; D:&#34; ... 可以找到原始代码here