I have the following class that enumerates all COM ports on the local PC, finding and storing only those with a friendly name that starts with the given prefix.
Now, assuming I know such COM ports are part of a composite device and that the composite device also has a network adapter, how can I find the network adapter associated with the given device? I’m sure there must be a relatively simple way of doing this (both devices will have the same parent node I think), but I’m not sure what the non-interop method would be… Can anyone assist?
Here is the class:
/// <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;
}
}
Thought I’d reply to my own, rather than deleting the question just in case someone else finds the answer useful.
It turns out the PNPDeviceID, a property present in both Win32_SerialPorts and Win32_NetworkAdapters contains an ID unique to the device, so it’s possible to identify them both. The solution is first to enumerate the serial ports, then extract the unique part of the PNPDeviceID and then to find all network adapters that are LIKE ‘%value%’, where value is part of the PNPDeviceID.
Turns out the number is the same for both, i.e.:
Serial Port PNPDeviceID = USB\VID_17DC&PID_0500&MI_02\8&18F2972&0&0002″
and
Network Adapter PNPDeviceID = USB\VID_17DC&PID_0500&MI_00\8&18F2972&0&0000″
, where the common ID is 18F2972.