Is it possible to determine the Win32_DiskDrive SerialNumber of the Environment.SpecialFolder.System drive?

拈花ヽ惹草 提交于 2019-12-06 11:33:46

You can use ManagmentObjectSearch combined with ASSOCIATORS OF statement:

public static string GetSerialNumber(string logicalDrive)
{
    using (var partitionsQuery = new ManagementObjectSearcher(string.Format("ASSOCIATORS OF {{Win32_LogicalDisk.DeviceID='{0}'}} WHERE ResultClass = Win32_DiskPartition", logicalDrive)))            
    {
        foreach (var results in partitionsQuery.Get())
        {
            using (var diskDrives = new ManagementObjectSearcher(string.Format("ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{0}'}} WHERE ResultClass=Win32_DiskDrive", results["DeviceID"])))
            {
                foreach (var d in diskDrives.Get())
                {
                    Console.WriteLine("Serial: " + d["SerialNumber"]);

                    return d["SerialNumber"].ToString();
                }
            }
        }
    }

    return null;
} 

Usage:

var num = GetSerialNumber(Path.GetPathRoot(Environment.SystemDirectory).TrimEnd(new [] {'\\'}));

Note: Dont forget to remove backslashes from the path returned by Path.GetPathRoot.

You could use the ManagementObjectSearcher class from System.Management then loop through the properties to find the serial number.

I think something along these lines will get you close to what you're looking for...

                var search = new ManagementObjectSearcher("select * from Win32_DiskDrive");
                foreach (var mo in search.Get())
                {
                    if (mo["SerialNumber"] != null)
                    {
                        return mo["SerialNumber"].ToString();
                    }
                }

https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-diskdrive

^ that should contain all the various properties you can get

Hope that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!