我有以下类枚举本地 PC 上的所有 COM 端口,仅查找并存储具有以给定前缀开头的友好名称的那些。
现在,假设我知道这样的 COM 端口是复合设备的一部分,并且复合设备也有一个网络适配器,我怎样才能找到与给定设备关联的网络适配器?我确信必须有一种相对简单的方法(我认为两个设备都将具有相同的父节点),但我不确定非互操作方法是什么......有人可以帮忙吗?
这是课程:
/// <summary>
/// A class to enumerate all COM ports through USB.
/// </summary>
public class SerialPortUSB
{
/// <summary>
/// Structure to store a port name and details.
/// </summary>
public struct PortName
{
public string Port;
public string Fullname;
public bool HadPrefix;
};
/// <summary>
/// Function to return all ports with the given prefix.
/// </summary>
/// <param name="prefix"></param>
/// <returns></returns>
static public List<PortName> PortsWithPrefix(string prefix)
{
List<PortName> ports = new List<PortName>();
try
{
// Select all COM ports.
ManagementObjectSearcher searcher = new ManagementObjectSearcher( "root\\CIMV2",
"SELECT * FROM Win32_SerialPort");
// Now iterate results looking for those that start with the prefix.
foreach (ManagementObject item in searcher.Get())
{
string friendlyName = (string)item["Caption"];
if (!friendlyName.StartsWith(prefix))
{
continue;
}
// Construct an item for this.
PortName name = new PortName();
int start = friendlyName.LastIndexOf('(') + 1, end = friendlyName.LastIndexOf(')');
name.HadPrefix = true;
name.Port = friendlyName.Substring(start, end - start);
name.Fullname = friendlyName;
ports.Add(name);
}
}
catch (ManagementException e)
{
// Failed to find any...
}
// Return the list of ports.
return ports;
}
}