您可以在“root\StandardCimv2”命名空间中使用新的 WMI 类MSFT_NetAdapter。此类是在Windows 8中引入的。
我们可以使用属性ConnectorPresent仅过滤到物理适配器。接下来我们必须消除 Wi-Fi 适配器(存在于物理适配器中),我们可以使用InterfaceType和/或NdisPhysicalMedium属性。
InterfaceType由 Internet 名称分配机构 (IANA) 定义,对于所有类似以太网的接口,其值为ethernetCsmacd (6)(参见https://www.iana.org/assignments/ianaiftype-mib/ianaiftype-mib)。
在NdisPhysicalMedium中,以太网适配器的值为0或802.3 (14)。
所以我在 C# 中的解决方案是:
try
{
var objectSearcher = new ManagementObjectSearcher("root\\StandardCimv2", $@"select Name, InterfaceName, InterfaceType, NdisPhysicalMedium from MSFT_NetAdapter where ConnectorPresent=1"); //Physical adapter
int count = 0;
foreach (var managementObject in objectSearcher.Get())
{
//The locally unique identifier for the network interface. in InterfaceType_NetluidIndex format. Ex: Ethernet_2.
string interfaceName = managementObject["InterfaceName"]?.ToString();
//The interface type as defined by the Internet Assigned Names Authority (IANA).
//https://www.iana.org/assignments/ianaiftype-mib/ianaiftype-mib
UInt32 interfaceType = Convert.ToUInt32(managementObject["InterfaceType"]);
//The types of physical media that the network adapter supports.
UInt32 ndisPhysicalMedium = Convert.ToUInt32(managementObject["NdisPhysicalMedium"]);
if (!string.IsNullOrEmpty(interfaceName) &&
interfaceType == 6 && //ethernetCsmacd(6) --for all ethernet-like interfaces, regardless of speed, as per RFC3635
(ndisPhysicalMedium == 0 || ndisPhysicalMedium == 14)) //802.3
{
count++;
}
}
return count;
}
catch (ManagementException)
{
//Run-time requirements WMI MSFT_NetAdapter class is included in Windows 8 and Windows Server 2012
}