简体   繁体   中英

How to get Device COM port information via WMI?

I want to get device COM port Information.

I can get some information using this code

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity"))
{
    foreach (ManagementObject currentObject in searcher.Get())
    {
        string caption = null;

        if (currentObject != null)
        {
            object currentObjectCaption = currentObject["Caption"];

            if (currentObjectCaption != null)
            {
                caption = currentObjectCaption.ToString();

                if (currentObjectCaption.ToString().Contains("(COM"))
                {
                    string key = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty);

                    caption = key + " (" + caption.Replace($"({key})", "").Trim() + ")";

                    if (comportInfo.ContainsKey(key) == false)
                        comportInfo.Add(key, caption);
                }
            }
        }
    }

but I can't get Device type and location

在此处输入图像描述

How to get location and deviceType infomation?

As present in MSDN, the Win32_PnPEntity class has the following properties ( https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-pnpentity )

You can see there's one for Manufacturer. 在此处输入图像描述

A sample example which gets the device and manufacturer's name. I'm not sure about Location. You can check if any other existing property helps.

using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%USB%'"))
{
    List<ManagementObject> mObjs = searcher.Get().Cast<ManagementObject>().ToList();
    foreach (var p in mObjs)
    {
        var manufacturer = p.GetPropertyValue("Manufacturer");
        var name = p.GetPropertyValue("Name");
        var sName = p.GetPropertyValue("SystemName");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM